Access.2007.VBA.Bibl..

(John Hannent) #1
In most of my Automation code working with other Office applications (Word, Excel,
and Outlook), I use the GetObjectfunction in the body of a procedure, to set a refer-
ence to the running instance of the application, if there is one; the procedure’s error handler runs
CreateObjectif the application is not already running (see the code samples later in this chapter
for examples). This prevents creation of multiple instances of Word, Excel, or Outlook.

If you don’t need any fancy formatting, just a plain text document, you can fill a blank Word docu-
ment with text using the TypeTextmethod. The FillWithTypeTextprocedure listed next
creates a blank Word document, then enters a document heading, then reads text from fields in an
Access table and writes it directly to the Word document, and finally applies some simple format-
ting, using Word commands:

Private Sub FillWithTypeText ()

On Error GoTo ErrorHandler

Dim appWord As Word.Application
Dim doc As Word.Document
Dim dbs As DAO.Database
Dim rst As DAO.Recordset

Set appWord = GetObject(, “Word.Application”)
Set doc = appWord.Documents.Add

Insert and format document title:

With appWord.Selection
.TypeText “Current Contacts as of “ _
& Format(Date, “Long Date”)
.TypeParagraph
.MoveLeft Unit:=wdWord, Count:=11, _
Extend:=wdExtend
.Font.Size = 14
.Font.Bold = wdToggle
.MoveDown Unit:=wdLine, Count:=1
End With

Insert a two-column table to hold contact data (one column for contact names, the other for user
comments):

doc.Tables.Add Range:=Selection.Range, _
NumRows:=1, _
NumColumns:=2, _
DefaultTableBehavior:=wdWord9TableBehavior, _
AutoFitBehavior:=wdAutoFitFixed
With appWord.Selection.Tables(1)
If .Style <> “Table Grid” Then
.Style = “Table Grid”
End If

NOTENOTE


Part I The Office Components and What They Do Best

Free download pdf