vbscript - 使用 VBScript 将 Word 文档中的文本替换为超链接

标签 vbscript hyperlink ms-word

我想替换 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/

相关文章:

if-statement - 在 vbscript 中,您可以在 if 语句中使用两个可能的条件吗? (或者)

http - 用于Web HTTP/HTTPS的基于永久ID的超链接方案,有多少种方法?

mysql - 从word文件导入数据以填充mysql数据库中的表

vba - 运行时错误 429,ActiveX 组件无法创建对象,自动化 MS Word 应用程序,CreateObject ("Word.Application")

asp-classic - ASP/VBScript "Gotchas"

excel - 生成多个 excel

vbscript - 在 Windows 7 中批量启动程序并按 Enter 键

php - 如何在 php/javascript 中打印输出时隐藏可见的超链接

VBA 在 Word 2010 中查找单词并替换为超链接

c# - 使用 XML 文件中的数据生成 Word 文档 (docx)/基于模板将 XML 转换为 Word 文档