使用VBScript用Hyperlinks替换Word文档中的文本 [英] To replace a text in word document with Hyperlinks, using VBScript
问题描述
我想在Word文档中的任何地方替换文本,例如'hello',并用Hyperlink替换-' http://www.google.com ".我正在使用替换功能来实现相同目的.我知道.Range()应该指向需要替换的文本.但是如何.以及如何将超链接参数传递给replace().
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
欢迎任何输入.
推荐答案
以下代码在Word-VBA中针对ActiveDocument/ThisDocument
的预期工作.我认为您可以轻松地将其用于VBScript子例程中.
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
这篇关于使用VBScript用Hyperlinks替换Word文档中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!