To replace a text in word document with Hyperlinks, using VBScript

a 夏天 提交于 2020-06-27 18:38:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!