Bookmarks in Visual Basic

* * *

This is an example of the use of bookmarks in a Visual Basic macro. A bookmark "current" is set at the beginning of the document. A program loop is then set up. In this loop the cursor is moved gradually to the right, and the "current" bookmark is set at the new cursor position each time, until the end of the document is reached.

'
' Go to beginning of document
'
Selection.HomeKey Unit:=wdStory
'
' Set "current" bookmark
'
ActiveDocument.Bookmarks.Add Name:="Current"
'
' While not end of document
'
'
While ActiveDocument.Bookmarks.Item("Current") <> "\EndOfDoc"
'
' Place cursor at current bookmark
'
ActiveDocument.Bookmarks("Current").Select
'
'
' Do whatever you want to do with the document
'
' For example:
'
' Clear marking and move cursor one to the right
' Set "current" bookmark at the new position in the document
' Move cursor back one and mark word found again
'
Selection.MoveRight Unit:=wdCharacter, Count:=1
ActiveDocument.Bookmarks.Add Name:="Current"
Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
'
' Perform some action on the document content.
'
Wend
'
' End of document reached
'
* *

Note:

"\EndOfDoc" is a pre-defined bookmark and indicates the end of the document.


Back to Visual Basic Tutorial:

Like some details on the programmer?