Tags

, ,

Bookmarks are a great way to specify important locations on the word document. Using VBA you can move the cursor to those bookmarks.


Creating Bookmarks Manually:

For example assume you have the following data in a word document:

Word Data
We want to be able to modify the value for each field using VBA for Word. Using bookmarks this process can be greatly simplified.

Step 1: Move the cursor before the name field:

Move Cursor Before Name Field

 Step 2: Create a bookmark:

Create Name Bookmark, 2

Create Name Bookmark
Step 3: Do the same for the other fields:

Create Bookmarks


VBA and Bookmarks:

Now that we have created bookmarks for the different fields in the last section we can easily modify each field. For example lets say we want to modify the name field to john. We could use the code below:

Sub main()
    Selection.GoTo What:=wdGoToBookmark, Name:="bmName"
    Selection.EndKey Unit:=wdLine, Extend:=wdExtend
    Selection.Text = " John" & vbCr
End Sub

Result:

Word VBA Change Name Field
The line below moves the cursor to the bookmark named “bmName”:

Selection.GoTo What:=wdGoToBookmark, Name:="bmName"

The line below selects text until the end of the line:

Selection.EndKey Unit:=wdLine, Extend:=wdExtend

For more information about selecting text in VBA for Word please see the link below:

The line below change the value of the selected text to “John”:

Selection.Text = " John" & vbCr

Example:

The code below will change the value in all the fields:

Sub main()
'change name
Selection.GoTo What:=wdGoToBookmark, Name:="bmName"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " New Name" & vbCr

'change last name
Selection.GoTo What:=wdGoToBookmark, Name:="bmLastName"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " New Last Name" & vbCr

'change address
Selection.GoTo What:=wdGoToBookmark, Name:="bmAddress"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " New Address" & vbCr

'change phone
Selection.GoTo What:=wdGoToBookmark, Name:="bmPhone"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " New Phone" & vbCr
End Sub

Result:

Result

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

Advertisements