Read and Delete Bookmarks in MS Word Document

Following code read all bookmarks name from a word document and list them into excel worksheet.

Read Bookmarks in MS Word Document
Sub ReadBookmarks()
    'Excel Objects
    Dim wb              As Excel.Workbook
    Dim ws              As Excel.Worksheet
    
    'Word Objects
    Dim wdApp           As Word.Application
    Dim objBookmark     As Word.Bookmark
    Dim objDoc          As Word.Document
    
    'Other Variables
    Dim strPath         As String
    Dim strFile         As String
    Dim r               As Long: r = 2
 
    Set wb = ActiveWorkbook
    Set ws = wb.ActiveSheet
 
    strFile = InputBox("Enter file path here: ", "")
    
    'Exit the program if no file is selected
    If strFile = vbNullString Then Exit Sub
    
    'Create word Application
    Set wdApp = CreateObject("Word.Application")
    
    'Open word document
    Set objDoc = wdApp.Documents.Open(Filename:=strFile)
    
    'read bookmarks in document and write to active sheet
    For Each objBookmark In objDoc.Bookmarks
        ws.Range("A" & r).Value = objDoc.Name
        ws.Range("B" & r).Value = objBookmark.Name
                      
        r = r + 1
    Next objBookmark
       
    objDoc.Close
    wdApp.Quit
        
End Sub

Delete all bookmarks from a word document using VBA in Excel or Word

Delete Bookmarks
Sub DeleteBookmarks()
    'Word Objects
    Dim wdApp           As Word.Application
    Dim objBookmark     As Word.Bookmark
    Dim objDoc          As Word.Document
    
    'Other Variables
    Dim strPath         As String
    Dim strFile         As String
    Dim r               As Long: r = 2
 
    strFile = InputBox("Enter file path here: ", "")
    
    'Exit the program if no file is selected
    If strFile = vbNullString Then Exit Sub
    
    'Create word Application
    Set wdApp = CreateObject("Word.Application")
    
    'Open word document
    Set objDoc = wdApp.Documents.Open(Filename:=strFile)
    
    'read bookmarks in document and write to active sheet
    For Each objBookmark In objDoc.Bookmarks
        objBookmark.Delete
    Next objBookmark
       
    objDoc.Close True
    wdApp.Quit
        
End Sub
Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *