首页 > 解决方案 > 在word中添加超链接后如何在VBA中重置样式

问题描述

我正在使用从这里https://wordribbon.tips.net/T000672_Making_Hyperlinks_from_Coded_Text.html改编的代码, 以根据匹配的文本自动生成 word 中的超链接。

我有一个问题,我想保留选择的原始格式(样式)。我试图开始工作的代码的关键部分是:

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

我正在尝试将当前样式存储在 curStyle 中,应用超链接,然后重置样式。

我得到了错误虽然“对象变量或块变量不是”

是否有一些技巧来存储样式应用超链接然后恢复原始样式?

标签: vba

解决方案


我可以提供两种选择

  1. 修改超链接样式(一次)
  2. 重置字体样式(之后)
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

推荐阅读