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 March 8, 2014)
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 way you can access macros is through the use of a button, added directly into the text of your document. This is done ...Discover More
Word allows you to create a macro that is run automatically whenever the program is started. If you want to bypass the ...Discover More
Need to figure out a date a certain number of days, weeks, months, or years in the future? It's easy to do using the ...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.