尋找文字的所有實例並使其成為帶有巨集的超鏈接

尋找文字的所有實例並使其成為帶有巨集的超鏈接

必需的

我想在 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

有了這個就很容易稱呼多個單字實例的 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

顯然,如果您想傳遞參數,您可以這樣做,以便可以使用您的參數來呼叫它,但這是您需要的基礎。

相關內容