带有超链接的 VBA 单词列表一行即可显示

问题描述 投票:0回答:1

在互联网上找到的以下代码适合我的目的,给出了一个书签列表作为这些书签的链接,但许多行都是空的,然后全部在一行上,即文档中的最后一行。我尝试了很多变体,并设法获得了书签列表,但没有指向这些书签的超链接。我可以根据要求提供后者,但不想混淆代码拒绝在条目之间创建段落分隔符的问题。 提前感谢任何明智的互动 克里斯 子内容1FrmBookmarksWLinks() 暗淡段落作为段落 暗淡书签 作为书签 调光范围 将链接文本变暗为字符串 ' 在文档末尾为书签列表创建一个新部分 设置 rng = ActiveDocument.Range rng.Collapse wdCollapseEnd rng.InsertBreak wdPageBreak ' 添加分页符以与现有内容分开

' Add a title to the new section
rng.InsertAfter "List of Bookmarks:" ' Title without extra line breaks
rng.Collapse wdCollapseEnd
rng.InsertParagraphAfter ' Insert a blank line after the title for clarity
rng.Collapse wdCollapseEnd

' Loop through all bookmarks in the document
For Each bookmark In ActiveDocument.Bookmarks
    ' Get the bookmark name
    linkText = bookmark.Name

    ' Create a clickable hyperlink to the bookmark
    ActiveDocument.Hyperlinks.Add _
        Anchor:=rng, _
        Address:="", _
        SubAddress:=linkText, _
        TextToDisplay:=linkText

    ' Insert a paragraph break after each hyperlink to ensure it appears on a new line
    rng.InsertParagraphAfter
    rng.Collapse wdCollapseEnd
Next bookmark

MsgBox "Bookmark list with links created."

结束子

vba ms-word hyperlink bookmarks tableofcontents
1个回答
0
投票

您的代码即将完成。请尝试修改后的脚本。

微软文档:

Characters.Last 属性(Word)

段落.最后一个属性(Word)

Sub ContentsFrmBook1marksWLinks()
    Dim para As Paragraph
    Dim bookmark As bookmark
    Dim rng As Range
    Dim linkText As String
    
    With ActiveDocument
        ' Add a page break to separate from the existing content
        .Characters.Last.InsertBreak wdPageBreak

        ' Add a title to the new section
        .Paragraphs.Last.Range.Text = "List of Bookmarks:"

        ' Loop through all bookmarks in the document
        For Each bookmark In .Bookmarks
            .Characters.Last.InsertParagraphAfter
            ' Get the bookmark name
            linkText = bookmark.Name
            ' Create a clickable hyperlink to the bookmark
            .Hyperlinks.Add _
                Anchor:=.Paragraphs.Last.Range, _
                Address:="", _
                SubAddress:=linkText, _
                TextToDisplay:=linkText
        Next bookmark
    End With
    MsgBox "Bookmark list with links created."
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.