Word VBA, Bookmarks
In this article I will explain the basics of working with bookmarks in VBA for word.
Contents
Creating Bookmarks:
Bookmarks can be created by using the Add method of the Bookmarks collection:
Bookmarks.Add ("bmName")
The input parameter to the Add method is a text string to name the bookmark.
Result:
The bookmark will be created at the location of the cursor at the time of calling the function.
Note: The Add method of the Bookmarks collection also accepts a second optional parameter. A range object. If passed the bookmark will be created at the start location of the range object rather than the current cursor location.
Example:
The code below creates a bookmark at the second line of the document. This is independant of the current position of the cursor:
Dim objRange As Range
Set objRange = Selection.GoTo(wdGoToLine, wdGoToFirst, 2)
Call Bookmarks.Add("bm2", objRange)
Deleting Bookmarks:
Bookmarks can be deleted using any of the methods below:
Method 1: Using the bookmark index. Bookmarks are indexed starting from the number 1:
Bookmarks.Item(1).Delete
Method 2: Using the bookmark name:
Bookmarks.Item("bmName").Delete
Method 3: Using a bookmark object:
Dim objBookmark As Bookmark
Set objBookmark = Bookmarks.Item(1)
objBookmark.Delete
Before:
After:
Check if Bookmark Exists:
If Bookmarks.Exists("bookmark Name") = True Then
MsgBox ("bookmark Exists")
Else
MsgBox ("bookmark does not exist")
End If
You can download the file and code related to this article from the link below:
See also:
If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com