Amirali Pm
Amirali Pm

Reputation: 1

Find everything between ( ) and turn it into a hyperlink

I need to find everything between parentheses and turn it into a hyperlink in which the string is "[Pmcid:"the thing"]" and the address is a url with "the thing" at the end of it.

I use wildcards in the search in the find section to find everything between parentheses.

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

How do I use that in a macro to make the hyperlink?

Upvotes: 0

Views: 43

Answers (1)

taller
taller

Reputation: 18762

  • Searching pattern can be simplified as \(*\)

Microsoft documentation:

Range.Find property (Word)

Hyperlinks.Add method (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

Upvotes: 0

Related Questions