Dragon Drop - A Visual Basic Software Consultancy

Software Clinic - VBA

Updating A Series Of Bookmarks


On one of the newsgroups someone had a question. How can they write some code which can change a set of bookmarks. The reason was that there was a requirement to put put into the document in a number of places the date.

The obvious solution would to place in the document template at the required places the 'CREATEDATE' field.

However, this is very limiting. For example, imagine a long legal document being created and prepared for a meeting early the following morning the CREATEDATE field would present the wrong date and it could be too much of a risk to get the document constructed in the early hours. So, quite clearly another method is required.


There are many ways around this problem and this particular solution is just one of many possibilites.

If the bookmarks were named so that, say, all of the Date bookmarks which were to be upated automatically all began with the same string, for example "bmkDate", then with a little VBA our problem could be solved.

In a module place the following code item.

Sub BookMarkRattle(sBookmark As String, sText As String)

  Dim oBookmark As Bookmark
  Dim sBookmarkName As String
  If Documents.Count > 0 Then
    For Each oBookmark In ActiveDocument.Bookmarks
      sBookmarkName = oBookmark.Name
      If InStr(1, sBookmarkName, sBookmark, vbTextCompare) = 1 Then
        oBookmark.Range.Text = sText
      End If
    Next oBookmark
  End If
End Sub

Then in the Document_New() event of the template put in some code such as:

Private Sub Document_New()

  Dim sDate As String
  sDate = InputBox("Please insert today's date", "Bookmark Example", Date)
  BookMarkRattle "bmkDate", sDate

End Sub

Then when the document is created the user is presented with a input box and whatever is entered in there goes into all of the bookmarks which start with "bmkDate".

Imagine the possibilities; one could have in legal documents the name of the plaintiff or defendant inserted into the correct place in the document. One could have the the licence plate details of a car in an insurance claim, the name of the vessel in a shipping manifest. The list is endless:

  BookMarkRattle "bmkPlaintiff", sPlaintiffName
  BookMarkRattle "bmkDefendant", sDefendantName
  BookMarkRattle "bmkLicencePlate", sLicencePlate	
  BookMarkRattle "bmkVesselName", sVesselName


This code can be downloaded from here.


If there are any suggestions for updates then please drop me a mail at malcolm.smith@dragondrop.com.