Reputation: 2245
I am using code that I have adapted from here https://wordribbon.tips.net/T000672_Making_Hyperlinks_from_Coded_Text.html to automatically generate hyperlinks in word based on matched text.
I have an issue though, I would like to preserve the original formatting (style) of the selection. The key part of the code which I am trying to get to work is:
Dim my_hyperlink As Hyperlink
Dim curStyle As Object
...
... ' find the text I want to match now apply hyperlink
With Selection
curStyle = .Style
Set my_hyperlink =ActiveDocument.Hyperlinks.Add(Anchor:=Selection.Range,_
Address:="https://example.com",SubAddress:="")
my_hyperlink.Range.Style = curStyle
End With
I am trying to store the current style in curStyle, apply the hyper link and then reset the style.
I am getting the error though "object variable or with block variable not "
Is there some trick to store the style apply hyperlink and then restore the original style?
Upvotes: 0
Views: 312
Reputation: 7627
I can offer two options to do it
Sub OldStyleHyperlinkStyleChange()
Dim my_hyperlink As Hyperlink
'...
'... ' find the text I want to match now apply hyperlink
With ActiveDocument.Styles(wdStyleHyperlink).Font
.ColorIndex = wdAuto
.Underline = wdUnderlineNone
End With
With Selection
Set my_hyperlink = ActiveDocument.Hyperlinks.Add(Anchor:=.Range, _
Address:="https://example.com", SubAddress:="")
End With
End Sub
Sub OldStyleReset()
Dim my_hyperlink As Hyperlink
'...
'... ' find the text I want to match now apply hyperlink
With Selection
Set my_hyperlink = ActiveDocument.Hyperlinks.Add(Anchor:=.Range, _
Address:="https://example.com", SubAddress:="")
my_hyperlink.Range.Font.Reset
End With
End Sub
Upvotes: 1