VBA:在Word中为超链接添加样式

时间:2018-11-29 08:28:47

标签: vba hyperlink ms-word

我试图制作一个宏,以根据级别(表中的新行中的每个链接)添加具有不同样式的超链接。

  1. hyperlinktext1(子样式1)(即粗体和16号)

    1.1超链接文本2(子样式2)(即尺寸14)

我已经确保样式存在并且可以用于普通文本,但是我无法将样式应用于通过VBA添加的超链接。

更改样式适用于由于某些原因手动添加的超链接。

    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")

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

插入超链接时,插入后的选择范围在超链接的末尾。因此,在代码中,当您应用样式时,就是将其应用到超链接末尾的插入点。

要获取超链接的范围,以便可以对其应用样式,可以移动选择范围的开始,或者更好地在插入超链接时捕获超链接。

在第一种情况下,您将添加行

Selection.MoveStart unit:=wdWord, count:=-1

在add语句之后和应用样式的行之前。

一种更好的执行任务的方法如下

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
相关问题