Access.2007.VBA.Bibl..

(John Hannent) #1
The Word Mail Merge option runs a wizard, which is generally similar to the one in the last two
Office versions. It offers you a choice of deselecting some records from the data source before per-
forming the merge, and you can create a new merge letter on the fly, so this interface choice can be
useful when you need to create a set of minimally formatted Word letters to recipients from an
Access table or query — but it may not be any easier to go through the six steps of the wizard,
compared with just creating a simple Access letter report based on a filtered query.

My conclusion, after reviewing the new data export features in Access 2007, is that (just as with
previous versions of Access) if you want to be able to select the records for an export of Access data
to Word, and to produce great looking documents that can be opened and possibly edited by all
Office users, you’re still best off writing VBA code to merge Access data to Word documents.

The Word Export.accdb sample database contains the tables, queries, forms, and code
used in this chapter.

Exporting Access Data to Word Using Automation Code ..................................................


Automation code is the tool you need to use when creating or working with Word documents in
Access VBA. Automation code is not a special programming language, just a set of functions used
in VBA code to work with the object models of other applications.

All Automation code starts with one of the two functions described as follows, either of which sets
a reference to a high-level Automation object. When working with Word, this is generally the Word
Application object.

The CreateObjectfunction with “Word.Application” as the Classargument creates a new
Word instance; it works whether or not Word is already open. The GetObjectfunction with
“Word.Application” as the Classargument attempts to set a reference to an existing instance
of Word. GetObjectsucceeds in setting a reference only if Word is already running.

To avoid creating multiple instances of Word, I use the GetObjectfunction in the body of a pro-
cedure, which sets a reference to an existing Word Application object, if Word is running, in com-
bination with an error handler that uses CreateObjectto create a new Word Application object
if GetObjectfails with Error 429, “ActiveX component can’t create object”:

Set appWord = GetObject(Class:=”Word.Application”)

[body of procedure here]

ErrorHandlerExit:
Set appWord = Nothing
Exit Sub

NOTENOTE


Part II Writing VBA Code to Exchange Data between Office Components

Free download pdf