让MS-Word vba ActiveDocument.Paragraphs(2)。仅选择第1段?

时间:2017-04-25 16:00:19

标签: vba hyperlink ms-word word-vba

我想通过VBA为我的MS-Word文件添加许多超链接,对于第1段,超链接是“./index/1.doc”,第2段是“./index/2.doc”,依此类推。简化程序是1)选择一个段落2)添加超链接,如下面的代码所示。但是,VBA代码为每个段落提供了相同的超链接,只应该用于最后一个段落。那么,有没有办法在VBA中取消选择来执行此案例?感谢

顺便说一句,VBA可以在任何包含1个以上段落的MS-Word文件上进行测试。

Sub addHypertext()
    For countParagraph = 1 To ActiveDocument.Paragraphs.Count
        Selection.Collapse Direction:=wdCollapseEnd    
        set para = ActiveDocument.Paragraphs(countParagraph)
        para.Select
        Set paraStyle = para.Style 
        ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, \
            Address:="./index/" & countParagraph & ".doc"    

        Rem this does not work 
        Rem Selection.Range.Style = paraStyle 

        Rem this does not work 
        Selection.Style = paraStyle 

        Rem this does not work too 
        Rem para.Style = paraStyle 

        Rem this produces "run-time error" 
        Rem para.Range.Style = "text"
    Next
End Sub

1 个答案:

答案 0 :(得分:1)

我看到发生了什么。它突出显示段落标记并使其成为超链接的一部分。我很好奇,如果你可能只是想在每个段落的末尾添加一个引用。看看这是否是你想要尝试的东西:

using

上面将在每个段落的末尾添加一个参考链接,就像维基百科在他们的网站上所做的那样。

以下内容将整个段落视为您最初想要的链接:

Sub addHypertext()
    Dim para As Paragraph

    For countParagraph = 1 To ActiveDocument.Paragraphs.Count
        Selection.Collapse Direction:=wdCollapseEnd
        Set para = ActiveDocument.Paragraphs(countParagraph)
        para.Range.Select
        Selection.MoveRight 1
        Selection.MoveLeft 1
        Selection.Font.Superscript = True
        Selection.TypeText "[" + Trim(Str(countParagraph)) + "]"
        Selection.MoveLeft Count:=Len("[" + Trim(Str(countParagraph)) + "]"), Extend:=wdExtend

        para.Range.Hyperlinks.Add Anchor:=Selection.Range, _
            Address:="./index/" & countParagraph & ".doc"

        Selection.Font.Superscript = False
    Next

End Sub

修改

要回答您对样式的补充,以下内容仍保留链接并更改样式。

Sub addHypertext()
    Dim para As Paragraph

    For countParagraph = 1 To ActiveDocument.Paragraphs.Count
        Selection.Collapse Direction:=wdCollapseEnd
        Set para = ActiveDocument.Paragraphs(countParagraph)
        para.Range.Select
        Selection.MoveEnd Count:=-1

        para.Range.Hyperlinks.Add Anchor:=Selection.Range, _
            Address:="./index/" & countParagraph & ".doc"

    Next

End Sub