Home > Blockchain >  VBA to add hyperlink to bookmark in MS-Word template
VBA to add hyperlink to bookmark in MS-Word template

Time:09-19

I need to add a hyperlink to a bookmark in an MS-Word template. The hyperlink (which changes depending on user input) points to an entry in a database on the web. I have no trouble building the hyperlink as a string variable, but I can't figure out how to put it in the bookmark so the user winds up with a Word document containing a link that can be clicked to go to the database entry. My code (below) just deletes the bookmark. What am I missing?

Dim databaseURL As String
' get databaseURL from an existing variable--this part works OK
databaseURL = ActiveDocument.Variables("databaseLink") 

' put the hyperlink in a bookmark named "linkToDatabase"
Dim BMRange As Range
Set BMRange = ActiveDocument.Bookmarks("linkToDatabase").Range
BMRange.Text = "Database link"

ActiveDocument.Hyperlinks.Add Anchor:=BMRange, _
                Address:=databaseURL, _
                SubAddress:="", ScreenTip:="", TextToDisplay:=BMRange.Text

CodePudding user response:

What you could do to simplify things is to have a bookmarked 'default' hyperlink field at the bookmarked range, then simply change the hyperlink field's code. For example:

ActiveDocument.Bookmarks("linkToDatabase").Range.Fields(1).Code.Text = "HYPERLINK " & databaseURL
  • Related