简体   繁体   中英

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

I found VBA to remove hidden bookmarks which works and tried to add DocumentBeforeClose as the trigger. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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