Replace Links with Images in Word

Working with links in MS Word - VBA or Python?

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

How would you replace links with images in MS Word? So here is the problem. There is a word document, with links to images. All these links need to be replaced with actual images.

I got this question on one of the forums for Python. Turns out, the poster wanted to do that for only one document right now and wants an easy way to repeat it later.

This is a typical developer problem. When you have been writing code for long, it’s hard to think beyond that language. We sometimes forget that there are better ways to do things if we just remember our objective.

So, here is my solution to this problem using VBA. Why not Python you may ask. Let’s get to that in a minute.

Sub ReplaceHyperlinkWithImage()

    Dim Lnk As Hyperlink
    Dim ext As String
    
    For Each Lnk In ActiveDocument.Hyperlinks
        ext = Right(Lnk.Address, 3) 
        If ext = "jpg" Or ext = "png" Then
            Lnk.Range.Select
            Selection.InlineShapes.AddPicture FileName:=Lnk.Address, _
                                              LinkToFile:=False, _
                                              SaveWithDocument:=True
        End If
    Next Lnk
End Sub

Now about using VBA, instead of Python.

If you create a macro, you can add a button to your Word Ribbon as I have shown earlier, and repeat this with one click.

If you have hundreds of files, Python will be a better solution.

PS: Above code will not be able to handle JPEG extension which is four characters. Should be easy though. Right? Leave a comment with your solution

Do you want to learn Web Scraping in ONE HOUR?

Sign-up now!

Leave a Reply

Your email address will not be published. Required fields are marked *

More To Explore

Ready To

Say bye to the boring courses that put you to sleep immediately.

Learn how to monitor online store prices, save data to CSV file, and even send mail alerts—all of this in less than 1 hour!

Enter your details to receive your invite for FREE.

small_c_popup.png

Get Free Material Now

Learn how we helped so may people Learn Python and land a job!