Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 22: Integrating Access with Other Applications


805


.MoveUp wdLine, 6
End With
‘Set the Word object to Nothing to free resources:
Set WordObj = Nothing
DoCmd.Hourglass False
End Sub

The MergeToWord function uses the With construct to reduce the amount of code used to refer-
ence the object variable. All the property and method references within the body of the With...
End With construct refer to the WordObj.Selection object. The WordObj object is set to
Nothing at the end of the subroutine to remove the Word Automation server from memory.

Creating an instance of a Word object
The first step in using Automation is to create an instance of an object. The sample creates an
object instance with the following code:

On Error Resume Next
...
Set WordObj = GetObject(, “Word.Application”)
If Err.Number <> 0 Then
Set WordObj = CreateObject(“Word.Application”)
End If

Obviously, you don’t want a new instance of Word created every time a thank-you letter is gener-
ated, so some special coding is required. This code snippet first attempts to create an instance by
using an active instance (a running copy) of Word. If Word is not a running application, an error
is generated. Because this function has On Error Resume Next for error trapping, the code
doesn’t fail; instead, it proceeds to the next statement. If an error is detected (the Err.Number is
not equal to 0 ), an instance is created by using CreateObject.

Cross-Reference
For information on handling errors, turn to Chapter 23.


Making the instance of Word visible
New instances of Word created with Automation code enables your application to exploit features
of Word without the user realizing that Word is running. In this case, however, you want to let the
user edit the merged letter, so Word needs to be made visible by setting the object’s Visible
property to True:

WordObj.Visible = True

Caution
If you don’t set the object instance’s Visible property to True, you may create hidden copies of Word that
use system resources and never shut down. A hidden copy of Word doesn’t show up in the Task tray or in the
Task Switcher.

Free download pdf