简体   繁体   English

Word VBA 关闭前删除隐藏书签

[英]Word VBA delete hidden bookmarks before closing

I want to set up a VBA so that for any document based on a template hidden bookmarks are deleted prior to the document closing.我想设置一个 VBA,以便在文档关闭之前删除基于模板的任何文档的隐藏书签。 We publish documents on our website.我们在我们的网站上发布文件。 They are written as Word and an API converts them to html. If there are hidden bookmarks they appear as links on the website (the hidden bookmarks convert to html anchors).它们以 Word 格式编写,API 将它们转换为 html。如果有隐藏书签,它们将在网站上显示为链接(隐藏书签将转换为 html 锚点)。 Currently we remove the bookmarks manual prior to the API, but this is time consuming (we publish 1000s of documents a year) and ineffective (people forget).目前我们删除了 API 之前的书签手册,但这很耗时(我们每年发布 1000 份文档)并且无效(人们忘记了)。

I found VBA to remove hidden bookmarks which works and tried to add DocumentBeforeClose as the trigger.我发现 VBA 可以删除有效的隐藏书签,并尝试将 DocumentBeforeClose 添加为触发器。 But it doesn't work:但它不起作用:

Private Sub DocumentBeforeClose(cancel As Boolean)

    Dim nBK As Long

    With ActiveDocument

        For nBK = .Bookmarks.Count To 1 Step -1

            If LCase(Left(.Bookmarks(nBK).Name, 3)) = "_hl" Then

                .Bookmarks(nBK).Delete

            End If

        Next nBK

    End With

    ActiveDocument.Save


End Sub

I went through Visual Basic Window, Normal, Microsoft Word Objects, ThisDocument.我浏览了 Visual Basic Window、Normal、Microsoft Word 对象、ThisDocument。

Nothing happens, the hidden bookmarks remain if I close and re-open the document.没有任何反应,如果我关闭并重新打开文档,隐藏的书签仍然存在。

I think you need to add this line:我认为你需要添加这一行:

.Bookmarks.ShowHidden = True

Like this it should work:像这样它应该工作:

Private Sub DocumentBeforeClose(cancel As Boolean)

Dim nBK As Long

With ActiveDocument

.Bookmarks.ShowHidden = True

    For nBK = .Bookmarks.Count To 1 Step -1

        If LCase(Left(.Bookmarks(nBK).Name, 3)) = "_hl" Then

            .Bookmarks(nBK).Delete

        End If

    Next nBK

End With

ActiveDocument.Save

End Sub

This has solved it:这已经解决了:

Sub AutoClose()

On Error Resume Next

Dim nBK As Long

With ActiveDocument

.bookmarks.ShowHidden = True

    For nBK = .bookmarks.Count To 1 Step -1

        If LCase(Left(.bookmarks(nBK).Name, 3)) = "_hl" Then

            .bookmarks(nBK).Delete

        End If

    Next nBK

End With

ActiveDocument.Save

End Sub

Only issue is that it tries to run when you open a document and puts up an error message that there is no active document.唯一的问题是它会在您打开文档时尝试运行并显示一条错误消息,指出没有活动文档。 'On error resume next' is to stop that error message 'On error resume next' 是停止该错误消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM