我想通过VBA为我的MS-Word文件添加许多超链接,对于第1段,超链接是"./index/1.doc",第二段是"./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发布于 2017-04-25 16:45:38
我知道发生了什么。它突出显示段落标记,并使其成为超链接的一部分。我很好奇,也许你只是想在每一段的末尾加上一个引用。看看这是否是你想尝试的东西:
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编辑
要回答您添加的样式,下面仍然保留链接并更改样式。
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"
para.Range.Select
Selection.MoveEnd Count:=-1
'Per your comments below for future visitors
Selection.Style = "Normal"
Selection.Style = "My Custom Style"
Next
End Subhttps://stackoverflow.com/questions/43615665
复制相似问题