查找文本的所有实例并使用宏使其成为超链接

查找文本的所有实例并使用宏使其成为超链接

必需的

我想在 MS Word 文档中查找单个文本的所有出现,将每个出现变为超链接,并将通用超链接样式更改为我选择的样式之一。

我拥有的

由于我不知道如何整体实现上述要求,因此我从其中的一部分开始,即找到一个单个实例并对其进行调整。

因此,我录制了一个宏,结果得到了以下代码。我修改了该代码,以便子程序可以接受参数超链接文本以及超链接子地址

Sub AutoDetectHyperlinksForText(hyperlinkText As String, subaddress As String, style As String)
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = hyperlinkText
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
        subaddress:=subaddress, ScreenTip:="", TextToDisplay:= _
        hyperlinkText
    Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
    Selection.Style = ActiveDocument.Styles(style)
End Sub

有了这个,很容易称呼多个单词实例的子项,例如:

Call AutoDetectHyperlinksForText("broadcasts", "_broadcastService", "Subtle Emphasis")

问题

我如何调整这个宏以便它检查整个文档?

附加问题

有没有办法修改上述脚本,以便我可以存储我的选择,并且不再需要.MoveLeft

用伪代码来说,它将是这样的:

Dim mySelect as Selection
mySelect = Selection.Find.Execute
ActiveDocument.Hyperlinks.Add Anchor:=mySelect.Range, Address:="", _
    subaddress:=subaddress, ScreenTip:="", TextToDisplay:= _
    hyperlinkText
mySelect.Style = ActiveDocument.Styles("Subtle Emphasis")

答案1

这将找到单词“google”(不是 googles 或 googled)并将其超链接到http:\\google.com

它也适用于风格

Sub FindAndHyperlink()
    'define the style
    Dim strStyle As String
    strStyle = "Subtle Emphasis"
    'set the search range
    Dim rngSearch As Range
    Set rngSearch = ActiveDocument.Range
    'set the search string
    Dim strSearch As String
    strSearch = "google"
    'set the target address for the hyperlink
    Dim strAddress As String
    strAddress = "http:\\google.com"

    With rngSearch.Find
        Do While .Execute(findText:=strSearch, MatchWholeWord:=True, Forward:=True) = True
            With rngSearch 'we will work with what is found as it will be the selection
                ActiveDocument.Hyperlinks.Add Anchor:=rngSearch, Address:=strAddress
                .Style = ActiveDocument.Styles(strStyle) 'throw the style on it after the link
            End With
            rngSearch.Collapse Direction:=wdCollapseEnd
            'keep it moving
        Loop
    End With
End Sub

显然,如果您想传递参数,您可以这样做,以便可以使用您的参数进行调用,但这是您需要的基础。

相关内容