找到 ( ) 之间的所有内容并将其变成超链接

问题描述 投票:0回答:1

我需要找到括号之间的所有内容,并将其转换为一个超链接,其中字符串是“[Pmcid:”the thing”]”,地址是一个以“the thing”结尾的网址。

我在查找部分的搜索中使用通配符来查找括号之间的所有内容。

([\(])(?@)([\)])

如何在宏中使用它来制作超链接?

vba ms-word hyperlink find-replace
1个回答
0
投票
  • 搜索模式可以简化为
    \(*\)

微软文档:

范围.查找属性(Word)

超链接.添加方法(Word)

Sub AddHyperlinksToParentheses()
    Dim doc As Document
    Dim rng As Range
    Dim match As Range
    Dim searchText As String
    Dim linkText As String
    Dim linkAddress As String
    Const BASE_URL = "https://www.w3schools.com/EXCEL/"
    ' Set the document
    Set doc = ActiveDocument
    Set rng = doc.Content
    ' Use Find to search for text in parentheses
    With rng.Find
        .ClearFormatting
        .Text = "\(*\)"
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchWildcards = True
        Do While .Execute
            Set match = doc.Range(rng.Start + 1, rng.End - 1)
            ' match.Select
            searchText = match.Text
            ' Create the display text and URL
            linkText = "[Pmcid:""" & searchText & """]"
            linkAddress = BASE_URL & searchText
            ' Add the hyperlink
            doc.Hyperlinks.Add _
                Anchor:=match, _
                Address:=linkAddress, _
                TextToDisplay:=linkText
            rng.Collapse Word.wdCollapseEnd
        Loop
    End With
End Sub

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.