问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/21499664/to-replace-a-text-in-word-document-with-hyperlinks-using-vbscript