我想在word文档中的任何地方替换文本,比如'hello',并用超链接替换它 - 'http://www.google.com'。我正在使用替换函数来实现相同的目标。我知道.Range()应该指向需要替换的文本。但是怎么样。我将如何将hyperlink参数传递给replace()。
这是缺陷代码的示例:
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
欢迎任何输入。
答案 0 :(得分:1)
以下代码在Word-VBA中为ActiveDocument/ThisDocument
按预期工作。我认为您可以轻松地将其用于VBScript子例程。
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