Using Word Templates for Creating Formatted Word Documents

The TypeText method used in the previous section is only suitable for creating very simple Word documents. If you need to produce fully formatted Word documents, with headers, footers, and sections with different margins, or if you need to place Access data at various points within blocks of text, it's best to prepare one or more Word templates in advance, formatting them as needed. Then you can create new documents from the templates and fill them with Access data as needed, using either bookmarks or (my preferred method) Word document properties.

The first step is to create the Word templates, with headers, footers, logo, and different fonts as needed. Depending on the method you want to use, either place bookmarks in the template where you want the Access data to appear or create document properties to accept the Access data, and place DocProperty fields in the template where you want the Access data to appear.

Bookmarks

As an example of using bookmarks in a Word template, I created a template designed to print on a certain type of paper (Paper Direct Milano), with a header and footer, several fonts, and two sections, the first for the letter itself and the second for a matching COM 10 envelope. I placed several bookmarks in the letter portion of the template, where the letter date, name and address, and salutation should print, and cross-reference fields in the envelope portion, to print the name and address there, as well as a PostNet ZIP bar code.

This chapter uses the new .dotx Word 2007 template format, which creates a document of the .docx type. Documents in this new Word format can only be used by people running Office 2007, so if you need to distribute Word documents to people running older versions of Office, it is best to use the .dot template format, and create .doc documents, which are usable in Office 97 through 2007.

Working with Word User Information Fields

You can place Word UserName and UserAddress fields in the document header to print your name and address. If you have used these fields in previous versions of Word, you may have difficulty locating them in the new Word 2007 interface, especially because Microsoft has chosen to put them in different places (in Word 2003, they were all conveniently located on the User Information tab of the Options dialog). In Word 2007, the user name is entered in the User Name field on the Personalize page of the Word Options dialog, which is opened from the Word Options button on the File menu.

Word 2007 Save Form Data
Entering the user name in the Word Options dialog.

continued continued

Curiously, the user address information is entered in a different location, as "Mailing address" at the bottom of the Advanced page of the Word Options dialog.

Personalize Proofing

Advanced

Trust Center

TBIB

iTl Copy remotely stored files < H] Allow background saves

Preserve fidelity when sharing this document:

ITl Save smart tags as XML properties in Web pages IH Save form data as delimited text file 0 Embed linguistic data [7] Embed smart ta^s

General

□ Con ivide feedback with sound ivide feedback with animation m file format conversion on open Update automatic links at open Irl Allow opening a document in Draft view IP] Allow background open of web pages 171 Enable .background repagination 0 Show add-in user interface errors

Mailing address: ¿1 Nowhere Drive

Somewhere, NY 12230

I File Locations.7] [ Web Oetions... | | Service Options... |

Compatibility options for: 9 Layout Opti

H 04702X ch06,d

Entering the mailing address (user address) in the Word Options dialog.

To place a field with the user name or user address into a template, select Field from the Quick Parts list in the Text group of the Insert menu.

Header Si Footer Tools

- "

X

Design

Property Field..

Q Building Blocks Organizer,,. • Get More on Office Online,..

i^j Save Selection to Quick Part Gallery...

Inserting a field into a template.

This opens the Field dialog (similar to the one in Word 2003), where you can select the User Name or User Address field for insertion.

Field

1 f IU-3.1

PI

ase choose a Held

Field properties

Field options

Categories:

New address:

m H

Field names:

Format

5ectionPages *

StyleRef

Subject

Symbol

Template

First capital Title case

No field options available for this field

TOA

Userinitials UserName

C Preserve formatting during updates

Description:

Address from Tools Options User Info

Field Codes

oc 1 arced

Li

Inserting the UserAddress field on a template.

The following figure shows the user name and address information in a template header.

Ji

fttt Milano

Letter.riotx - Microsoft Word

- -

»

Home

1 Insert

1 Page Layout

Rcfmn

es Mailings

Review View Developer

œ

Ë) Pages

1-1 SmartArt

Picture

¡if)Chart

Footer T Page Number *

-I Parts " Li& 5 '—^ ^JWordArt* ¡f| Text

Box- =Drop Cap ^ •

a

is

==

' "'"I

5

---------------

————

n

Helen Feddema 21 Nowhere Drive Somewhere, NY 12230

Phone: (555) 111-2222

f

_

fl 1

■™

|nl, , —Î

A template header with user name and address information from Word user information fields.

To insert a bookmark in a document or template, select Bookmark from the Links group on the Insert tab, as in Figure 2.2.

It is advisable to uncheck the "Preserve formatting during updates" checkbox when inserting fields, as otherwise you can get different fonts or sizes for the text displayed in the fields.

the fields.

FIGURE 2.2

Opening the Bookmark dialog.

FIGURE 2.2

Type the bookmark name in the Bookmark dialog and click Add (Figure 2.3).

FIGURE 2.3

Creating a bookmark.

FIGURE 2.3

Creating a bookmark.

By default, you won't see the I-beam markers that indicate bookmarks in a Word document; to see them, check the "Show bookmarks" checkbox on the Advanced page of the Word Options dialog, as depicted in Figure 2.4.

FIGURE 2.4

Turning on bookmark display in the Word Options dialog.

FIGURE 2.4

Turning on bookmark display in the Word Options dialog.

Figure 2.5 shows the second (envelope) page of the Milano Word template, with user information fields, bookmarks, and a BarCode field (to see these fields, press Alt+F9).

FIGURE 2.5

Fields and bookmarks on a Word template.

FIGURE 2.5

Fields and bookmarks on a Word template.

,1 r r?T In code for this chapter's sample database, the assumption is that the Word templates MBaAXflflt are located in the default folder, which is C:\Users\User Name\AppData\Roaming\ Microsoft\Templates for Windows Vista or C:\Documents and Settings\User Name\Application Data\Microsoft\Templates for Windows XP. For a more flexible method of setting the Templates folder, see Chapter 6.

The form frmContacts in the sample Access to Word database displays contacts located in the U.S.A. The form, shown in Figure 2.6, has three buttons, each of which creates a letter to the selected contact using a different method.

FIGURE 2.6

The Contacts form with buttons to create Word letters.

FIGURE 2.6

The Contacts form with buttons to create Word letters.

Generate Reports Word Macro Vba

The code for creating a document using bookmarks is listed as follows: Private Sub cmdBookmarks_Click() On Error GoTo ErrorHandler

Dim appWord As Word.Application

Dim doc As Word.Document

Dim dbs As DAO.Database

Dim rst As DAO.Recordset

Dim strTemplatePath As String

Dim strTemplateName As String

Dim strTemplateNameAndPath As String

Dim lngContactID As Long

Dim strRecipientName As String

Dim strRecipientAddress As String

Dim strRecipientZip As String

Dim strPrompt As String

Dim strTitle As String

Dim strSalutation As String

Dim fso As New Scripting.FileSystemObject

Dim fil As Scripting.File

IngContactID = Nz(Me![ContactID]) If lngContactID = 0 Then strPrompt = "No contact selected" strTitle = "Problem"

MsgBox strPrompt, vbOKOnly + vbExclamation, strTitle GoTo ErrorHandlerExit Else strRecipientName = Nz(Me![FirstNameFirst]) strRecipientAddress = Nz(Me![RecipientAddress]) strSalutation = Nz(Me![FirstName]) strRecipientZip = Nz(Me![PostalCode]) End If

Set appWord = GetObject(, "Word.Application")

Get the default User Template path from the Word Options dialog (it is still available in code, though it has disappeared from the Word 2007 interface):

strTemplatePath = _

appWord.Options.DefaultFilePath(wdUserTemplatesPath) _ & "\"

Debug.Print "Templates folder: " & strTemplatePath strTemplateName = "Milano Letter (Bookmarks).dotx" strTemplateNameAndPath = strTemplatePath & strTemplateName

On Error Resume Next

Try to locate the template in the default Templates folder, and put up a message if it is not found:

Set fil = fso.GetFile(strTemplateNameAndPath) If fil Is Nothing Then strPrompt = "Can't find " & strTemplateName _ & " in " & strTemplatePath & "; canceling" MsgBox strPrompt, vbCritical + vbOKOnly GoTo ErrorHandlerExit End If

On Error GoTo ErrorHandler

Set doc = appWord.Documents.Add(strTemplateNameAndPath)

Write information to Word bookmarks in the document:

With appWord.Selection

.Goto what:=wdGoToBookmark, Name:="LetterDate" .TypeText Text:=Format(Date, "Long Date")

.Goto what:=wdGoToBookmark, Name:="RecipientName" .TypeText Text:=strRecipientName

.Goto what:=wdGoToBookmark, Name:="RecipientAddress" .TypeText Text:=strRecipientAddress

.Goto what:=wdGoToBookmark, Name:="RecipientZip" .TypeText Text:=strRecipientZip

.Goto what:=wdGoToBookmark, Name:="Salutation" .TypeText Text:=strSalutation

.Goto what:=wdGoToBookmark, Name:="EnvelopeName" .TypeText Text:=strRecipientName

.Goto what:=wdGoToBookmark, Name:="EnvelopeAddress" .TypeText Text:=strRecipientAddress

.Goto what:=wdGoToBookmark, Name:="EnvelopeZip" .TypeText Text:=strRecipientZip

Reinsert the EnvelopeZip bookmark so the zip code will be available for use by the bar code field on the envelope:

.MoveLeft Unit:=wdWord, Count:=3, Extend:=wdExtend doc.Bookmarks.Add Range:=Selection.Range, _ Name:="EnvelopeZip"

.Goto what:=wdGoToBookmark, Name:="LetterText" strPrompt = "Ready to enter letter text" strTitle = "Access data imported" MsgBox strPrompt, vbOKOnly, strTitle appWord.Visible = True appWord.Activate

End With

ErrorHandlerExit:

Set appWord = Nothing Exit Sub

ErrorHandler:

Word is not running; open Word with CreateObject:

Set appWord = CreateObject("Word.Application") Resume Next Else

& "; Description: " & Err.Description Resume ErrorHandlerExit End If

End Sub

Document Properties

When you use Word document properties rather than bookmarks to write Access data to a Word document, you don't need to have two (or more) sets of bookmarks, one for each place you want to display a piece of data (for example, displaying the recipient's name and address on the letter and the envelope). You can write the data to a document property once and display it in multiple places in the Word document with DocProperty fields.

To create the properties, first select Finish from the File menu in the template, and select Properties, as shown in Figure 2.7.

FIGURE 2.7

Opening the Document Information panel.

FIGURE 2.7

Opening the Document Information panel.

This opens the Document Information panel, with a few of the more common document properties displayed (see Figure 2.8).

FIGURE 2.8

The Document Information panel.

FIGURE 2.8

The Document Information panel.

To get to the Properties sheet, select Advanced from the Properties drop-down at the top of the panel; this opens the Properties sheet, which looks much the same as in Word 2003. Click the Custom tab (Figure 2.9) to start creating document properties.

FIGURE 2.9

The Custom page of the Word Properties sheet.

FIGURE 2.9

To create a document property, enter its name (no spaces), select the type, enter a value (a space will do for a Text property), and then click Add. Figure 2.10 shows the doc properties for the Milano Letter (Doc Props) template.

FIGURE 2.10

The Doc properties for the Milano Letter (Doc Props) template.

FIGURE 2.10

Next, place DocProperty fields in the template where you want the values in the doc properties to display.

One bookmark is still needed, even if you are using doc properties to display data from Access: The BarCode field needs to reference a bookmark in order to create the PostNet bar code. Therefore, after placing a DocProperty field for the zip into the template, select that field and create a bookmark for it.

To insert a DocProperty field, select QuickParts from the Text group on the Insert tab of the Ribbon, select DocProperty as the field type, and then select the doc property from the Property list (see Figure 2.11).

Don't give your doc properties the same names as any built-in properties, although Word lets you do this, because this will make it difficult to select the correct property from the list of properties, which includes both built-in and custom doc properties.

Figure 2.12 shows the first page of the template, with DocProperty fields displayed, and one bookmark to indicate the place where the letter text is to be typed.

FIGURE 2.11

Inserting a DocProperty field.

Field

1 » Itearf

PI

ase choose a field

Field properties

Field options

Categories:

Property:

(All)

-

Keywords LastPrinted LastSavedBy

-

Field names:

Citation

Comments

Compare

CreateDabe

Database

Date

Manager

NameofApplication ODMADodd

I

No field options available for this field

l> 1 ■■

Paragraphs

Eq

RedpientZip RevisionNumber

GoToButton GreetingLine Hyperlink If

O Preserve formatting during updates

Description:

Insert the value of the property chc

sen in Options

Field Codes

|N,OK | | CamJ

The first page of the Milano Letter (DocProps) template, with User information and DocProperty fields.

How Create Custom Msgbox

The code that creates the document with text written to doc properties is listed as follows:

Private Sub cmdDocProps_Click()

On Error GoTo ErrorHandler

Dim appWord As Word.Application

Dim doc As Word.Document

Dim dbs As DAO.Database

Dim rst As DAO.Recordset

Dim strTemplatePath As String

Dim strTemplateName As String

Dim strTemplateNameAndPath As String

Dim lngContactID As Long

Dim strRecipientName As String

Dim strRecipientAddress As String

Dim strRecipientZip As String

Dim strPrompt As String

Dim strTitle As String

Dim strSalutation As String

Dim fso As New Scripting.FileSystemObject

Dim fil As Scripting.File

Dim prps As Object lngContactID = Nz(Me![ContactID]) If lngContactID = 0 Then strPrompt = "No contact selected" strTitle = "Problem"

MsgBox strPrompt, vbOKOnly + vbExclamation, strTitle GoTo ErrorHandlerExit Else strRecipientName = Nz(Me![FirstNameFirst]) strRecipientAddress = Nz(Me![RecipientAddress]) strSalutation = Nz(Me![FirstName]) strRecipientZip = Nz(Me![PostalCode]) End If

Set appWord = GetObject(, "Word.Application")

Get the default User Templates path from the Word Options dialog:

strTemplatePath = _

appWord.Options.DefaultFilePath(wdUserTemplatesPath) _ & "\"

Debug.Print "Templates folder: " & strTemplatePath strTemplateName = "Milano Letter (Doc Props).dotx" strTemplateNameAndPath = strTemplatePath & strTemplateName

On Error Resume Next

Try to locate the template in the default Templates folder, and put up a message if it is not found:

Set fil = fso.GetFile(strTemplateNameAndPath) If fil Is Nothing Then strPrompt = "Can't find " & strTemplateName _ & " in " & strTemplatePath & "; canceling" MsgBox strPrompt, vbCritical + vbOKOnly GoTo ErrorHandlerExit End If

On Error GoTo ErrorHandler

Set doc = appWord.Documents.Add(strTemplateNameAndPath) Write information to Word doc properties:

Set prps = doc.CustomDocumentProperties prps.Item("LetterDate").Value = Format(Date, "Long Date") prps.Item("RecipientName").Value = strRecipientName prps.Item("RecipientAddress").Value = strRecipientAddress prps.Item("RecipientZip").Value = strRecipientZip prps.Item("Salutation").Value = strSalutation

Update fields:

With appWord

.Selection.WholeStory .Selection.Fields.Update .Selection.HomeKey unit:=wdStory End With appWord.Selection.Goto what:=wdGoToBookmark, _

Name:="LetterText" strPrompt = "Ready to enter letter text" strTitle = "Access data imported" MsgBox strPrompt, vbOKOnly, strTitle appWord.Visible = True appWord.Activate

ErrorHandlerExit:

Set appWord = Nothing Exit Sub

ErrorHandler:

Word is not running; open Word with CreateObject:

Set appWord = CreateObject("Word.Application") Resume Next

Else

& "; Description: " & Err.Description Resume ErrorHandlerExit End If

End Sub

0 0

Post a comment