1
votes

I'm trying to search through a word document and replace regex matches with a series of static hyperlinks.

For example, if I get a regex match for "A-1", I want to replace the "A-1" string with a hyperlink with Anchor = "A-1" and Address = "https://www.my_website.com/A-1". My RegEx matches could be "A-1", "A-2", "A-3", etc.

I'm familiar with RegEx but I'm very new to VBA. What I have so far:

Sub FindAndHyperlink()

    Dim RegEx As Object
    Set RegEx = CreateObject("VBScript.RegExp")

    RegEx.Global = True
    RegEx.Pattern = "([A][\-])([0-9])"

    Set Matches = RegEx.Execute(ActiveDocument.Range.Text)
    For Each Match In Matches
        ActiveDocument.Range.Text = RegEx.Replace(ActiveDocument.Range.Text, (ActiveDocument.Hyperlinks.Add Anchor:=Match, Address:="https://www.my_website.com/" & Match))
    Next

End Sub

This doesn't compile because it's expecting a ) after ActiveDocument.Hyperlinks.Add.

I think the problem is that the RegEx.Replace() method is expecting (String, String) arguments rather than (String, Hyperlink object), but I'm not sure the best way to get around that.

Any help would be appreciated.

2
I don't think replace makes sense for what you're trying to do. I think it'd make more sense to clear the text at Match.Range and then instead add the hyperlink at the location of the Match.Range - Marcucciboy2
@Marcucciboy2 how would you do that? I'm thinking something like 'For Each Match In Matches' 'Match.Text = ""' ActiveDocument.Hyperlinks.Add Anchor:=Match, Address:="my_website.com" & Match' - UCanCallMeBob89
Does Matches actually receive a range from RegEx.Execute of each match for that regex? - Marcucciboy2
Yeah, that's what I'm thinking I'd go for - Marcucciboy2
You cannot do that with regex alone, the regex only works on plain text. Find the index in the document and try to add a hyperlink at that position. - Wiktor Stribiżew

2 Answers

1
votes

Try:

Sub FindAndHyperlink()
Application.ScreenUpdating = False
Const HLnk As String = "https://www.my_website.com/"
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "A-[0-9]{1,}"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    .Hyperlinks.Add Anchor:=.Duplicate, Address:=HLnk & .Text, TextToDisplay:=.Text
    .Start = .Hyperlinks(1).Range.End
    .Find.Execute
  Loop
End With
Application.ScreenUpdating = True
End Sub
0
votes

I just tested this and it worked fine for me.

([a-z _:/.A-Z-1-9]+)

enter image description here

Notice the UPPERCASE and lowercase, plus the 1-9 (one through nine, inclusive), as well as the characters such as slash and period.