Please Note: This article is written for users of the following Microsoft Word versions: 97, 2000, 2002, and 2003. If you are using a later version (Word 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Word, click here: Setting a VBA Variable from a Bookmark.
by Allen Wyatt
(last updated October 25, 2018)
As part of a macro, you may have a need to work with information stored in a bookmark. For instance, you may need to extract the text in a bookmark, assign it to a variable, and then do some processing based on the variable contents.
There are two ways you can assign the contents of a bookmark to a variable in a VBA macro. The first is to simply jump to the bookmark and select it, then make the variable equal to the contents of the selection. The following code lines will perform this action for a bookmark named MyBookmark:
Dim sMyString As String Selection.GoTo What:=wdGoToBookmark, Name:="MyBookmark" sMyString = Selection.Text
If you don't want to change the selection within the document, you can also simply work with the Bookmarks collection maintained by Word. Assuming you still need the contents of the MyBookmark bookmark, the following code will do the trick:
Dim sMyString As String sMyString = ActiveDocument.Bookmarks("MyBookmark").Range.Text
WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (1595) applies to Microsoft Word 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Word (Word 2007 and later) here: Setting a VBA Variable from a Bookmark.
Learning Made Easy! Quickly teach yourself how to format, publish, and share your content using Word 2013. With Step by Step, you set the pace, building and practicing the skills you need, just when you need them! Check out Microsoft Word 2013 Step by Step today!
One of the properties that Word maintains for a document is a title. If you want this title displayed on the title bar ...Discover More
Need to format your document using a macro? You can easily set the right margin for an individual paragraph by using the ...Discover More
Need to rename a disk file from within a macro? You can do it using the Name command, described in this tip.Discover More
FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."
Got a version of Word that uses the menu interface (Word 97, Word 2000, Word 2002, or Word 2003)? This site is for you! If you use a later version of Word, visit our WordTips site focusing on the ribbon interface.