Example Access VBA preparing a Word document using Range Bookmarks

mdlueck

Sr. Application Developer
Local time
Today, 06:36
Joined
Jun 23, 2011
Messages
2,648
Greetings,

I thought to share some code I have been working on today. The syntax from Access VBA is a bit different than one example I finally located on a site about Word explaining how to successfully use Bookmarks and leave the inserted text inside of the named Bookmark. Webpage which finally had the details:

"Working with Bookmarks in VBA"
http://word.mvps.org/faqs/macrosvba/WorkWithBookmarks.htm

My Access VBA code is using Late Bindings - I do NOT have the Reference turned on for Word 2007.

Also I have this code in a Class Module, so copy/pasting code from several methods, skipping copying the simple code wrapping class variables into class properties. So, will NOT compile as-is verbatim. Still, should be very helpful for those interested in driving Microsoft Word from Microsoft Access VBA and utilizing Bookmarks which encapsulate the text placed into the Bookmark locations.

Code:
  Dim strASLWeeklyStatusFilename As String
  Dim objWordApp As Object
  Dim objWordDoc As Object

  'Get pointer to Word Object
  Set objWordApp = CreateObject("Word.Application")

  'Open the document
  Set objWordDoc = objWordApp.Documents.Open(Me.ASLWeeklyStatusFilename)

  'Make Word Instance visible
  objWordApp.Visible = True

  Dim strBMName As String
  Dim objBMRange As Object

  strBMName = "HdrProjectName"
  Set objBMRange = objWordDoc.Bookmarks(strBMName).Range
  objBMRange.Text = ObjProjectsTbl.title
  objWordDoc.Bookmarks.Add Name:=strBMName, Range:=objBMRange
  Set objBMRange = Nothing

  strBMName = "HdrDate"
  Set objBMRange = objWordDoc.Bookmarks(strBMName).Range
  objBMRange.Text = Format(datetimeutils_MondayOfThisWeek, "mm/dd/yyyy")
  objWordDoc.Bookmarks.Add Name:=strBMName, Range:=objBMRange
  Set objBMRange = Nothing

  'Save the document
  objWordApp.ActiveDocument.Save

  'Bye bye!
  objWordApp.Quit

  Set objWordDoc = Nothing
  Set objWordApp = Nothing
 

Users who are viewing this thread

Back
Top Bottom