Microsoft Office Tutorials and References
In Depth Information
Merging Data with a Word Document
Next, use the syntax described in “Using the Application object,” earlier in
this chapter, to open an instance of Microsoft Word. Here’s the code:
Book IX
Chapter 1
‘Declare and set Word object variables
Dim Wrd As New Word.Application
Set Wrd = CreateObject(“Word.Application”)
After opening an instance of Word, set the location of the Word template
that created earlier (see “Creating a Word template,” earlier in this chapter).
You use the Path property of Application.CurrentProject to get the
location and then concatenate it with the filename. For this example, we
named the Word template file WordMergeDocument.dotx, as follows:
‘Specify Path to Template
Dim sMergeDoc As String
sMergeDoc = Application.CurrentProject.Path & _
“\WordMergeDocument.dotx”
This code assumes that you saved the Word template file in the same folder
as the Access database.
Next, use the Add method of the Application.Documents object to create
a new document based on the template file. After creating a new Word
document, set the Visible property of the Wrd object to true, letting the user
see Word. When you open Word from VBA, it’s invisible to the user unless
you specify otherwise, as follows:
‘Open Word using template and make Word visible
Wrd.Documents.Add sMergeDoc
Wrd.Visible = True
After viewing the document, use the Bookmarks collection within the
ActiveDocument to add the values from Access. Replace the CurrentDate
bookmark with the system date, using the Date() function. Then replace
the AccessAddress and AccessSalutation bookmarks with the variables
set earlier in the code, as follows:
‘Replace Bookmarks with Values
With Wrd.ActiveDocument.Bookmarks
.Item(“CurrentDate”).Range.Text = Date
.Item(“AccessAddress”).Range.Text = sAccessAddress
.Item(“AccessSalutation”).Range.Text = sAccessSalutation
End With
Finally, switch to Print Preview view, and clean up the code in Word. Figure 1-7
shows the document with the bookmarks replaced by data from Access.
Search JabSto ::




Custom Search