VBA find word and replace with a Hyperlink in Word 2010

mr3k picture mr3k · May 26, 2014 · Viewed 8.3k times · Source

I've a word document with some text. At some paragraphs I've words that I want to add the hyperlink to. Here's an example:

The book "When the sun goes up", ABC-1212321-DEF, have been released today.......

The "ABC-1212321-DEF" should be found and apply a hyperlink as follows: http://google.com/ABC-sometext-1212321-anothertext-DEF

All the strings in the document starts with "ABC-" and ends with "-DEF".

Thanks in advanced.

EDIT:

This is what I've got this far:

Sub InsertLinks()
Dim r As Range
Dim SearchString As String

Set r = ActiveDocument.Range
SearchString = "ABC-"
With r.Find
.MatchWildcards = True
Do While .Execute(findText:=SearchString, Forward:=True) = True
ActiveDocument.Hyperlinks.Add Anchor:=r, _
Address:=Replace(r.Text, " ", ""), _
SubAddress:="", ScreenTip:="", TextToDisplay:=r.Text
With r
.End = r.Hyperlinks(1).Range.End
.Collapse 0
End With
Loop
End With
End Sub

This now detects ABC- and add some random link. But need to get the number between ABC- and -DEF. The length is not the same.

Answer

mr3k picture mr3k · May 27, 2014

SOLUTION

This is the code that solved my problem:

Sub InsertLinksTB()
Dim Rng As Range
Dim SearchString As String
Dim EndString As String
Dim Id As String
Dim Link As String


Set Rng = ActiveDocument.Range
SearchString = "ABC-"
EndString = "-DEF"
    With Rng.Find
    .MatchWildcards = True
        Do While .Execute(findText:=SearchString, Forward:=False) = True
            Rng.MoveStartUntil ("ABC-")
            Rng.MoveEndUntil (" ")
            'MsgBox (Rng.Text)
            Id = Split(Split(Rng.Text, "ABC-")(1), "-DEF")(0)
            'MsgBox (Id)
            Link = "http://google.com/" & Id

                ActiveDocument.Hyperlinks.Add Anchor:=Rng, _
                Address:=Link, _
                SubAddress:="", ScreenTip:="", TextToDisplay:=Rng.Text
                Rng.Collapse wdCollapseStart


        Loop
    End With

End Sub

So if the text "ABC-1234-DEF" is found in the text, it will hyperlink this text with http://google.com/1234

Hope this is helpful for someone.