Reputation: 1
I'm trying to make a macro to add hyperlinks with different styles depending on level, each link on a new row in a table.
hyperlinktext1 (sub style1) (i.e bold and size 16)
1.1 hyperlinktext2 (sub style2) (i.e size 14)
I have made sure that the styles exist and work for normal text but I can't get it to work with applying a style to a hyperlink added with VBA.
Changing styles works on hyperlinks I manually add for some reason.
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _
"file.pdf", SubAddress:="", ScreenTip:="", TextToDisplay:="text1"
Selection.Style = ActiveDocument.Styles("Sub level1")
'new row
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.InsertRows 1
Selection.Collapse Direction:=wdCollapseStart
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _
"file2.pdf", SubAddress:="", ScreenTip:="", TextToDisplay:="text2"
Selection.Style = ActiveDocument.Styles("Sub level2")
Any suggestions?
Upvotes: 0
Views: 1107
Reputation: 4355
When you insert a hyperlink the selection range after the insertion is at the end of the hyperlink. So in your code, when you apply your style, you are applying it to an insertion point at the end of your hyperlink.
To get the range of the hyperlink, so that you can apply a style to it, you can either move the start of the selection range, or better, capture the hyperlink when it is inserted.
In the first case you would add the line
Selection.MoveStart unit:=wdWord, count:=-1
after the add statement and before the line that applies the style.
A better way to carry out your task is as below
Option explicit
Sub test()
InsertHyperlinkWithStyle Selection.Range, "c:\path_to\file", ActiveDocument.Styles("Sub level1")
End Sub
Sub InsertHyperlinkWithStyle(this_range As Word.Range, this_file_path As String, this_style As Word.Style)
Dim my_hyperlink As Hyperlink
Set my_hyperlink = ActiveDocument.Hyperlinks.Add( _
Anchor:=this_range.Duplicate, _
Address:=this_file_path, _
TextToDisplay:="text1")
my_hyperlink.Range.Style = this_style
End Sub
Upvotes: 1