2

I would like to replace a text ,say, 'hello', anywhere in a word document and replace it with Hyperlink - 'http://www.google.com'.I am using a replace function to achieve the same. I understand that the .Range() should be pointing to the text that needs to be replaced. But how. And how will I pass the hyperlink argument to the replace().

Here a sample of the defective code :

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\Test\Test_Hyperlink.docx")
Set objRange = objDoc.Range()
'passing the text to be found 'hello' and hyperlink to be replaced
FnSearchAndReplaceText "hello", (objDoc.Hyperlinks.Add objRange, " http://www.google.com", , ,)

Function FnSearchAndReplaceText(argFindText, argReplaceText)
Const wdReplaceAll = 2
    Set objSelection = objWord.Selection
    objWord.Visible = True
    objSelection.Find.Text = argFindText        
    objSelection.Find.Forward = TRUE
    objSelection.Find.MatchWholeWord = True
    objSelection.Find.Replacement.Text = argReplaceText
    objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
End Function

Any input is welcome.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Naveen Rajeev
  • 77
  • 2
  • 8
  • 1
    Please, let's make it clear- you want to replace each `hello` with which text? or you want to make each `Hello` a link to Google.com? Anyway, it will not go in the way you expect. To help you I need clarification. – Kazimierz Jawor Feb 01 '14 at 18:43
  • I have changed the text. Hope it makes sense. – Naveen Rajeev Feb 03 '14 at 13:44

1 Answers1

2

The following code works as expected in Word-VBA for ActiveDocument/ThisDocument. I think you could easily adopt it to use in VBScript subroutine.

Sub Replace_text_Hyperlink()

    Dim txtToSearch
    Dim txtHyperLink
    Dim txtNew

        txtToSearch = "hello"
        txtHyperLink = "http://www.google.com"

    ThisDocument.Content.Select

    With Selection.Find
        .ClearFormatting
        .Text = txtToSearch
        .Forward = True
        .Wrap = wdFindStop
    End With

Do While Selection.Find.Execute
    Selection.Text = "'http://www.google.com'"     'your new text here
    ActiveDocument.Hyperlinks.Add Selection.Range, txtHyperLink  'but hyperlink is created here
Loop

End Sub
Kazimierz Jawor
  • 18,861
  • 7
  • 35
  • 55
  • KazJaw, Thank you very much for replying to this post! I do not have any experience in VBA myself, but managed to put together based on your fine inputs into VBScript. I have marked your's as the answer. Really appreciate it. Ciao ! – Naveen Rajeev Feb 12 '14 at 16:30