1
votes

I trying to replace or search and add hyperlink to specyfy sentence in Word document. I try using this codes. Anyway code is changing only first finding word, not all in document:

       Dim r As Word.Range
    r = Globals.ThisAddIn.Application.ActiveDocument.Content
    With r.Find
        .ClearFormatting()
        .Text = ("MyWordA MyWordB")
        .MatchWholeWord = True
        .Forward = True
        .Execute()
        'If .Found = True Then r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")
        Do While .Execute(Forward:=True) = True
            r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")
            'r.Font.ColorIndex = Word.WdColorIndex.wdBlue 'works for all(?)
        Loop
    End With

Eaven when I want to find only single word in loop for, then code find first one:

    doc = Globals.ThisAddIn.Application.ActiveDocument
    Dim r As Word.Range = doc.Range
    Dim ww As Word.Range
    For Each ww In r.Words
        If ww.Text = "MyWord" Then _
          ww.Hyperlinks.Add(ww, "http:\\www.whatever", , "Displayed text")
    Next

Anyone could tell me how I can search all text to replace/add hyperlinks to all text I was looking for?

1

1 Answers

1
votes

The problem is that you keep finding the same text over and over again. Within your loop, after adding the hyperlink, you need to move the range after the added hyperlink. The simplest way to do this is to collapse the range by calling

r.Collapse(WdCollapseDirection.wdCollapseEnd)

To troubleshoot issues like this it is helpful to select the current range so that you can see what is going on.

Do While .Execute(Forward:=True) = True

    ' select range for troubleshooting
    r.Select()
    r.Hyperlinks.Add(r, "http:\\www.whatever", , "Displayed text")

    ' move the range after the link
    r.Collapse(WdCollapseDirection.wdCollapseEnd)
Loop