我想替换 Word 文档中任意位置的文本,例如“你好”,并将其替换为超链接 - ' http://www.google.com '.我正在使用替换函数来实现相同的目的。我知道 .Range() 应该指向需要替换的文本。但如何。我将如何将超链接参数传递给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
欢迎任何意见。
最佳答案
以下代码在 ActiveDocument/ThisDocument
的 Word-VBA 中按预期工作。我认为您可以轻松地采用它在 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
关于vbscript - 使用 VBScript 将 Word 文档中的文本替换为超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21499664/