very new to this and would be grateful for your help. I'm trying to write a Word macro in Visual Basic that will replace every instance of a pattern with a hyperlink derived from the pattern. The pattern is of the form 123 WORD 4568, where the WORD is always the same but the numbers (and quantity of numbers) changes. E.g. 1948 WORD 12, 231 WORD 3948, 92 WORD 1029.
The hyperlink depends on the number, so for e.g. 1948 WORD 12 it's something like www.word.com/1948/12.html
Using wildcards, I can easily find all instances of the pattern and replace them with a hyperlink to just word.com:
Sub InsertLinksTB()
Set Rng = ActiveDocument.Range
With Rng.Find
SearchString = "[0-9]{1,9} WORD [0-9]{1,9}"
.MatchWildcards = True
Do While .Execute(findText:=SearchString, Forward:=False) = True
Link = "www.word.com"
ActiveDocument.Hyperlinks.Add Anchor:=Rng, _
Address:=Link, _
SubAddress:="", ScreenTip:="", TextToDisplay:=Rng.Text
Rng.Collapse wdCollapseStart
Loop
End With
End Sub
I can't figure out what to do with SubAddress to generate the full hyperlink for each instance of the pattern, given the wildcards.
Again, really grateful for any help. Thanks!
CodePudding user response:
If the pattern is always the same, you can use the Split
function to get the elements of the string and construct the link.
Sub InsertLinksTB()
Set Rng = ActiveDocument.Range
With Rng.Find
SearchString = "[0-9]{1,9} WORD [0-9]{1,9}"
.MatchWildcards = True
Do While .Execute(findText:=SearchString, Forward:=False) = True
Link = "www.word.com/" & Split(Rng.Text, " ")(0) & "/" & Split(Rng.Text, " ")(2) & ".html"
ActiveDocument.Hyperlinks.Add Anchor:=Rng, _
Address:=Link, _
SubAddress:="", ScreenTip:="", TextToDisplay:=Rng.Text
Rng.Collapse wdCollapseStart
Loop
End With
End Sub