0
votes

My VBA script is searching for a specific text in a Word document and if the found text contains a Hyperlink, I want to copy also the Hyperlink to the new document.

I have tried to do (source is a table in word and so is destination):

With source.Cell(1,1).Range
   .Find.Text = "MyTextToSearch
   .Find.Execute Forward:=True
   .Select
   .Copy
End With
destination.Cells(1).Range.Paste

The text is copied to the destination but without the hyperlink. When I do the same in Word using Find and Copy and Paste (via GUI), everything is copied to the destination

Any suggestions?

1

1 Answers

0
votes

Word finds the searched for text not in the document, as it were, but in the Hyperlink. So, when you copy the text you get the found text, and if you want the hyperlink you must specify the hyperlink to be copied. The following code makes this distinction.

Dim Rng As Word.Range
Dim Fnd As Boolean

Set Rng = ActiveDocument.Tables(1).Cell(1, 1).Range
With Rng
   .Find.Text = "This is my text"
   Fnd = .Find.Execute(Forward:=True)
End With

If Fnd Then
    If Rng.Hyperlinks.Count Then
        Set Rng = Rng.Hyperlinks(1).Range
    End If
    Rng.Copy
    ActiveDocument.Tables(1).Cell(5, 1).Range.Paste
End If