View Single Post
 
Old 12-24-2019, 12:16 PM
noslenwerd noslenwerd is offline Windows 10 Office 2016 for Mac
Novice
 
Join Date: Dec 2019
Posts: 15
noslenwerd is on a distinguished road
Default Using VBA to find html img code, and insert images dynamically

I am repurposing code that macropod had authored in a previous post for finding html for links, and converting the hyperlinks with custom text in a word document.

For reference that code is below:

Code:
Sub ConvertHyperlinks()
Dim StrAddr As String, StrDisp As String
' Turn Off Screen Updating
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .Text = "\<[Aa] href=([!\>]@)\>([!\<]@)\</a\>"
    .ClearFormatting
    .Replacement.ClearFormatting
    .Replacement.Text = ""
    .Forward = True
    .MatchWildcards = True
    .Wrap = wdFindStop
    .Execute
  End With
  Do While .Find.Found = True
    StrAddr = Replace(Replace(Replace(Split(Split(.Text, ">")(0), "=")(1), Chr(34), ""), Chr(147), ""), Chr(148), "")
    StrDisp = Split(Split(.Text, ">")(1), "<")(0)
    .Hyperlinks.Add Anchor:=.Duplicate, _
      Address:=StrAddr, TextToDisplay:=StrDisp
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
' Restore Screen Updating
Application.ScreenUpdating = True
End Sub
I am trying to repurpose that code to do the same for html code for images.

Essentially I want the macro to find all instances of <img src="c:\users\8172837\worksheet\test.jpg">, and embed that image into the document.

Below is the code I came up with, but I am running into issues. Admittedly I am not understanding the wildcards that macropod used here, but I tried researching to the best of my abilities.

Code:
Sub ConvertImages()
Dim StrAddr As String
' Turn Off Screen Updating
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .Text = "\<img src=([!\>]@)\>"
    .ClearFormatting
    .Replacement.ClearFormatting
    .Replacement.Text = ""
    .Forward = True
    .MatchWildcards = True
    .Wrap = wdFindStop
    .Execute
  End With
  Do While .Find.Found = True
    StrAddr = Replace(Replace(Replace(Split(Split(.Text, ">")(0), "=")(1), Chr(34), ""), Chr(147), ""), Chr(148), "")
	InlineShapes.AddPicture FileName:=StrAddr, LinkToFile:=False
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
' Restore Screen Updating
Application.ScreenUpdating = True
End Sub
Reply With Quote