Axonn
Axonn

Reputation: 10336

VBA: Can't change SubAddress property of Hyperlinks in Word Document

I'm trying to fix the hyperlinks in a Word document. I need to change the SubAddress property of some hyperlinks. To that end, I'm looping through them. Unfortunately, I get a very weird error saying method 'subaddress' of object 'hyperlink' failed when I try to change any SubAddress. Apparently this happens because something is broken with VBA itself.

Sub FixHyperlinks()
'
' FixHyperlinks Macro
'
'
ActiveDocument.Hyperlinks(1).SubAddress = "some new subaddress"
End Sub

I'm rocking Office 2016 Professional Plus. Can anybody tell me if this works for you?

It's easy to test. Just create a new document, type two one-word lines. Make the second line style "Heading 1". Go to first line, hit CTRK + K (to create hyperlink) point it to "a place in this document", select the heading you just created. DO NOT enter any address. Now go to Macros, paste the above and hit F5 while your caret is inside the code.

The hyperlink works fine when clicked with the mouse (first line hyperlink will take you to the 2nd line Heading).

Upvotes: 2

Views: 974

Answers (2)

Michel Abi Raad
Michel Abi Raad

Reputation: 41

There is a flaw with this property. It works only if the Address property is set to a non-empty string. So, to make the property work (i.e., modifiable), set the Address property to a non-empty string (such as a space) and then you can modify the SubAddress property, such as:

ActiveDocument.Hyperlinks(1).Address = " "    ' Space

ActiveDocument.Hyperlinks(1).SubAddress = "some new subaddress"   

Upvotes: 1

macropod
macropod

Reputation: 13505

Although Hyperlink.SubAddress Property is supposed to be a read/write string, writing to it fails - even in Word 2010. Try something along the lines of:

Dim Rng As Range, StrAddr As String, StrTxt As String
With ActiveDocument
  With .Hyperlinks(1)
    Set Rng = .Range
    StrAddr = .Address
    StrTxt = .TextToDisplay
    .Delete
  End With
  .Hyperlinks.Add Anchor:=Rng, Address:=StrAddr, SubAddress:="new_sub_address"
End With

Upvotes: 1

Related Questions