【问题标题】:Find particular strings in a word document and hyperlink to pdf's located in the ActiveDocument.Path在 Word 文档中查找特定字符串并超链接到位于 ActiveDocument.Path 中的 pdf
【发布时间】:2019-02-01 15:15:51
【问题描述】:

我的例子就是这样。我有一个看起来像这样的word文档:

ERN.001.001.0001

苹果和橙子

ABC.001.001.0002

ERN.001.001.0004

草莓

ERN.001.001.0005

同样在 ActiveDocument.Path 中,我有以下文件:

ERN.001.001.0001.pdf、ABC.001.001.0002.pdf、ERN.001.001.0004.pdf、ERN.001.001.0005.pdf

我想创建一个脚本,在 word 文档中查找 pdf 文档并将它们超链接回目录。

我当前的代码如下所示:

Sub AddHyperlinks()
Dim r1 As Range

Dim SearchString As String

        SearchString = "[A-Z]{1-3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,4}"

        Set r1 = ActiveDocument.Content

With r1.Find
        .ClearFormatting
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .Text = SearchString


Do While .Execute(Forward = True) = True
        r1.Hyperlinks.Add Anchor:=r1, _
        Address:=ActiveDocument.Path & "\" & r1.Text & ".pdf", _
        SubAddress:="", ScreenTip:="", TextToDisplay:=r1.Text

        r1.Collapse wdCollapseStart


Loop

End With
End Sub

当我运行此脚本时,它会找到 SearchString,但它似乎不明白我要超链接的内容。有人对我做错了什么有任何想法吗?

【问题讨论】:

    标签: vba pdf hyperlink ms-word find


    【解决方案1】:

    将此代码复制并粘贴到您的 VBA 编辑器中,然后运行宏“CreateLinks”。 你的模式似乎也错了,我不知道为什么它对你有用......

    Sub CreateLinks()
    
    Dim Rng As Range: Set Rng = ActiveDocument.Range
    Dim SearchString$, Link$
    Dim strPath$: strPath = ActiveDocument.Path & "\"
    
    SearchString = "[A-Z]{3}[.][0-9]{3}[.][0-9]{3}[.][0-9]{4}" ' If the text characters are not fixed, then use: [A-Z]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,4}
        With Rng.Find
        .MatchWildcards = True
            Do While .Execute(findText:=SearchString, Forward:=False) = True
                Link = strPath & Rng & ".pdf"
    
                    ActiveDocument.Hyperlinks.Add Anchor:=Rng, _
                    Address:=Link, _
                    SubAddress:="", ScreenTip:="", TextToDisplay:=Rng.Text
                    Rng.Collapse wdCollapseStart
    
            Loop
        End With
    End Sub
    

    编辑 - 结果:

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多