Word Bookmarks – VBA Macros to Add, Delete, Goto, Modify
Add Bookmark
This Word macro will add a bookmark:
Sub AddBookmark()
ActiveDocument.Bookmarks.Add "automateexcel_com_01"
End Sub
Delete Bookmark
This VBA macro will delete a bookmark:
Sub DeleteBookmark()
If ActiveDocument.Bookmarks.Exists("automateexcel_com_01") Then 'we need to check if bookmark named "automateexcel_com_01" exists in active doc
ActiveDocument.Bookmarks(Index:="automateexcel_com_01").Delete
End If
End Sub
Go To Bookmark
This simple macro will go to a bookmark:
Sub GoToBookmark()
If ActiveDocument.Bookmarks.Exists("automateexcel_com_01") Then 'we need to check if bookmark named "automateexcel_com_01" exists in active doc
Selection.GoTo What:=wdGoToBookmark, Name:="automateexcel_com_01"
End If
End Sub
Modify Bookmark
This macro will modify a bookmark's content:
Sub ModifyBookmarkContent()
' change bookmark contents
' more complicated, because changing bookmark range content will delete bookmark
Dim oRangeBKM As Range
If ActiveDocument.Bookmarks.Exists("automateexcel_com_01") Then 'we need to check if bookmark named "automateexcel_com_01" exists in active doc
'Identify current Bookmark range and insert text
Set oRangeBKM = ActiveDocument.Bookmarks("automateexcel_com_01").Range
oRangeBKM.Text = "automateexcel.com"
'Make again the bookmark
ActiveDocument.Bookmarks.Add "automateexcel_com_01", oRangeBKM
End If
End Sub
This is a modify bookmark function:
Sub UpdateBookmarkContent(strBookMarkName As String, strNewText As String)
' "usable' procedure for add in
Dim oRangeBKM As Range
If ActiveDocument.Bookmarks.Exists(strBookMarkName) Then 'we need to check if bookmark named "automateexcel_com_01" exists in active doc
'Identify current Bookmark range and insert text
Set oRangeBKM = ActiveDocument.Bookmarks(strBookMarkName).Range
oRangeBKM.Text = strNewText
'Make again the bookmark
ActiveDocument.Bookmarks.Add strBookMarkName, oRangeBKM
End If
End Sub
You can call the function by adding the bookmark name and new text as arguments:
Sub CallBookmarkFunction()
Call UpdateBookmarkContent("automateexcel_com_01", "automateexcel.com")
End Sub