1

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?

1 Answer 1

1
  • 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.