Merging from access to word

You can export data from your Access database to a Microsoft Word document by using the Export — RTF File Wizard. This article explains how to use the Export — RTF File Wizard and how to save your export settings as a specification for later reuse.

In this article

  • Exporting data to Word: the basics

  • Export data to Word

  • Understand how Access exports objects to Word

  • What else should I know?

Exporting data to Word: the basics

You can export a table, query, form, or report to Microsoft Word. When you export an object by using the Export — RTF File Wizard, Access creates a copy of the object’s data in a Microsoft Word Rich Text Format file (*.rtf). For tables, queries, and forms, the visible fields and records appear as a table in the Word document. When you export a report, the wizard exports the report data and layout  — it tries to make the Word document resemble the report as closely as possible.

  • Start the operation from Access    To export data from Access to Word, you need to work in Access. There is no functionality in Word that can import data from an Access database. You also cannot save an Access database or table as a Word document by using the Save As command in Access.

  • Objects you can export    You can export a table, query, form, or report. You can also export only the records selected in a view. You cannot export macros and modules. When you export a form or datasheet that contains subforms or subdatasheets, only the main form or datasheet is exported. You need to repeat the export operation for each subform and subdatasheet that you want to view in Word. Conversely, when you export a report, subforms and subreports that are included in the report are exported, along with the main report.

  • Outcome of the operation    The Export — RTF File Wizard always exports formatted data. This means that only the fields and records that are visible in an object or view are exported along with the display format settings. Columns and records that are hidden, due to filter settings, are not exported. For a report, the layout of the report is also preserved when it is exported.

  • Merging with an existing document    When you export from Access to a Word document, the data is always exported into a new Word file. If you want the data to be inserted into an existing Word document, you must first export it from Access into a new Word document, and then copy the data from the new Word document and paste it into the existing document. Alternatively, you can copy rows directly from an Access table, query, form, or report, and then paste them into your existing document.

Export data to Word

The process of exporting data to a Word document follows these broad steps:

  • Prepare your source data for the export. As part of this step, you make sure that your data does not contain errors, and you decide whether to export some or all of the data in your source table.

  • Run the Export — RTF File Wizard.

  • Optionally save your settings as an export specification for later reuse.

The steps in the following sections explain how to perform each task.

Prepare for the export

  1. Open the source Access database.

  2. In the Navigation Pane, select the object that contains the data you want to export.

    You can export a table, query, form, or report.

  3. Review the source data to ensure that it does not contain error indicators (green triangles) or error values, such as #Num.

    Ensure that you have resolved any errors before you export the data to Word. Otherwise, you will find that such values are replaced with a null value.

  4. If the destination Word document exists and is open, close it before you continue. The wizard prompts you before overwriting the document.

    Note: You cannot append data to an existing Word document.

  5. In the Access database, if you want to export only a portion of a table, query, or form, open the object and select just the records you want.

Export the data

  1. On the External Data tab, in the Export group, click Word.

  2. The Export — RTF File export wizard opens.

    Select a destination and export options on the Export - RTF File dialog box.

    Note: The Export commands are available only when a database is open.

  3. In the Export — RTF File wizard, specify the name of the destination file.

  4. The wizard always exports formatted data. If you want to view the Word document after the export operation is complete, select the Open the destination file after the export operation is complete check box.

  5. If you selected the records that you want to export before you started the export operation, you can select the Export only the selected records check box. However, if you want to export all the records in the view, leave the check box cleared.

    Note: This check box appears unavailable (dimmed) if no records are selected.

  6. Click OK.

  7. If the destination document exists, you are prompted to click Yes to overwrite the file. Click No to change the name of the destination file, and then click OK again.

Access exports the data and opens the destination document in Word, depending on the export options you specified in the wizard. Access also displays the status of the operation on the final page of the wizard.

Understand how Access exports objects to Word

The following table describes how Access exports various objects and values to Word. This can help you determine what is going wrong if the export operation is not working the way you expect.

Item

Export considerations

Field names

When you export a table, a query, or a form, the field names are placed in the first row of the table in the Word document. When you export a report, the placement of the field names in the Word document varies with the report layout.

Multivalued fields

A field in Access that supports multiple values is exported to a single column in Word. The values are separated by commas (,).

Pictures, objects, and attachments

All graphical elements — logos, data in OLE object fields, and attachments that are part of the source data  — are not exported.

Graphs

Microsoft Graph objects are not exported.

Expressions

Expressions are not exported to the Word document. Only the results of the expressions are exported.

Subforms and subdatasheets

When you export a form or datasheet, only the main form or datasheet is exported. You must repeat the export operation for each subform and subdatasheet.

What else should I know?

  • For information on how to save the details of your export into a specification that you can reuse later, see the article Save the details of an import or export operation as a specification.

  • For information on how to run saved export specifications, see the article Run a saved import or export operation.

  • For information on how to schedule specifications to run at specific times, see the article Schedule an import or export operation.

  • For information on how to change a specification name, delete specifications, or update the names of source files in specifications, see the article Manage Data Tasks.

Top of Page

Table of Contents

  • 1 How do I link an Access database to Word?
  • 2 How do I mail merge labels from access?
  • 3 How do I view merge fields in Word?
  • 4 What is a merge letter?
  • 5 How do I do a mail merge in Word 2016?

How do I link an Access database to Word?

To link data or to avoid using Access altogether, use Word’s Database toolbar instead of the Clipboard as follows:

  1. Open a blank Word document and display the Database toolbar by choosing Toolbars from The View menu and then selecting Database.
  2. Click Insert Database on the Database toolbar.

How do I insert a merge field in Word?

Adding Simple Merge Fields

  1. Open a Microsoft Word document.
  2. Click where you want to place a merge field.
  3. In the Insert tab, click Quick Parts and then Field….
  4. Under Categories, select (All).
  5. Under Field names, select MergeField.
  6. Type the name of the merge field under Field name.
  7. Click OK.

How do I mail merge labels from access?

Print Access data by using the Mail Merge Wizard in Microsoft Word

  1. In the Navigation Pane, select the table or query that contains the data you want to print.
  2. On the External Data tab, in the Export group, click Word Merge.

Can you mail merge from Access to Word?

Open the Access database that contains the addresses you want to merge with Word. The Microsoft Word Mail Merge Wizard dialog box opens. Choose whether you want the wizard to link your address data into an existing Word document, or to start with a new, blank document. Click OK.

How do I view merge fields in Word?

  1. Open the document.
  2. Select Tools, Options from the menu bar.
  3. Select the View tab and mark the Field Codes checkbox.
  4. Change the Field shading option to Always and click OK.

How do you review what a merge will look like?

Here’s how to work things:

  1. On the Mailings tab, in the Preview Results group, click the Preview Results command button.
  2. When things don’t look spiffy, click the Preview Results button again and then edit the main document.
  3. Peruse the records.
  4. Click the Preview Results command button again to exit Preview mode.

What is a merge letter?

Mail merge consists of combining mail and letters and pre-addressed envelopes or mailing labels for mass mailings from a form letter.

What are the three advantages of mail merge?

Advantages….

  • one standard letter can be written and sent to all customers without having to manually add each name and address.
  • the letter can be personalised – it looks as though the letter has been written to the individual person.
  • it’s a very fast way to produce hundreds of personalised letters.

How do I do a mail merge in Word 2016?

How to Mail Merge in Office 2016

  1. Make sure your contacts list is ready.
  2. Create a new blank document in Word.
  3. Navigate to the Mailings tab.
  4. Click the Start Mail Merge button and select your document type.
  5. Click the Select Recipients button and choose to create a new list, use an existing list, or choose from Outlook Contacts.

Microsoft Access, Microsoft Word /
Documents, Microsoft Access, Microsoft Word, Word-Processing /

    
1 January 2010

How to successfully merge data from Access to Word.

Q:  Bruce Michael writes:  “I have been attempting to do a merge in Word 2003 using an Access 2003 query.  When I look in the query, the data is correct, but when I actually merge using the data, for one column in the database, the values that come up are from another column.  I have checked, and changed the field name in access to no avail.  I couldn’t find anything in the MS Knowledgebase that seemed to cover this problem.  Have you come across anything like it?”

A:  This might have to do with a lookup field in a table, which takes the value in the linked table.  I generally prefer to do merges in VBA code, which gives me complete control over what gets merged where.  You might want to look at my Code Sample #24, which demonstrates how to merge data from Access to Word using doc properties (my favorite method), mail merge, bookmarks and TypeText.  Also Access Archon #92, Mail Merge Mysteries, if you want to stick with mail merge.

Another thing you could try is making a make-table query based on the query, and then using the table it generates for the merge.

There are plenty of ways to print Access data without getting into VBA. The usual method is to just create a report from the Access database window. You can also use the Microsoft Word Mail Merge Wizard to print form letters, envelopes, labels, and catalogs from any Access table or query. There’s no VBA involved in any of that. Just learn to use Word’s Mail Merge feature, and you’re on your way.

Yet a third approach would be to create a general Word template that contains bookmarks (placeholders) for data to be filled in later. Then, use VBA in Access to replace the bookmarks with data from an Access table. This is particularly handy when you want to be able to click a button on a form in Access to print one Microsoft Word form letter.

Creating the Word template

The first step to merging data from Access into a Word document is to create a Word document template (DOT file). Start with any blank Word document and type your form letter (or whatever you wish) as you normally would in Word. You can use any and all Word features — fonts, pictures, tables, WordArt, whatever.

Wherever you want VBA to insert data from an Access table, create a Word bookmark. A bookmark (in Word) is just a placeholder. Bookmarks are usually hidden, so before you add any bookmarks to the document, choose ToolsO Options from the Word menu bar. In Word’s Options dialog box that opens, click the View tab, select Bookmarks, and then click OK.

You can insert bookmarks however you wish. Here’s how I usually do it:

1. Move the cursor to where you want VBA to insert data from Access.

2. Type a short, simple name for the bookmark.

The name cannot contain spaces nor punctuation, and it must start with a letter.

3. Select (double-click) the name you just typed and then press Ctrl+C to copy it.

4. Choose InsertOBookmark from the Word menu bar.

5. Press Ctrl+V to paste the typed name as the bookmark name.

6. Click the Add button.

You’ll need to go through those steps for each item of data that you want VBA to insert later. In the example shown in Figure 14-7, I add three bookmarks to the document. Note that the square brackets around each bookmark’s name are visible because the Show Bookmarks option is on. I didn’t type any of those square brackets.

The bookmark names in the sample document template get data from Access and VBA as follows:

1 TodaysDate: VBA will replace this bookmark with the current date.

1 AddressLines: VBA will replace this line with as many lines as necessary to show the recipient’s address.

1 Salutation: VBA will replace this with the customer’s first name or just Sirs if the first name is Null (empty) in the record being printed.

When you finish typing your document and all your bookmarks are in place, follow these steps to save the document as a Word template:

1. Choose FileOSave As from Word’s menu bar.

2. From the Save As Type option at the bottom of the Save As dialog box, choose Document Template (*.dot).

3. Use the Save In drop-down list to navigate to the folder in which you want to store the document template.

Your best bet would be to put it in the same folder as your database MDB file, but you can use any folder you wish — provided that you know the full path to the document. For example, if you put the Word template in your Shared Documents folder, the path to that document is C:Documents and SettingsAll UsersDocuments.

4. Name the document (but don’t change the .dot extension) and click the Save button.

I name my document template WordFormLetter.dot, but you can name yours however you wish.

5. Close Microsoft Word.

So that takes care of the Word document. The rest of the action takes place in Access and VBA.

Bookmarks

Figure 14-7:

Word document template with bookmarks to later accept Access data.

WordFormLetter.dot (Read

Only) — Microsoft Word

File Edit View insert

Normal + Arial I t Arial Narrow

(format lools Table Window Help Type a question for help tsfflnraii^Elir — © _

— 12 — B I D m m m ■ t= — =E :E it □ — S — A — .

File Edit View insert

Normal + Arial I t Arial Narrow

(format lools Table Window Help Type a question for help tsfflnraii^Elir — © _

— 12 — B I D m m m ■ t= — =E :E it □ — S — A — .

1234-Arbitrary Highway Randomville, CA 98765

TodaysDate —

AddressUneE

Dear Salutation —

The main body of th Each Item In the squ shown inside the bre Customers table.

e letter starts here, and can contain any text, fonts, and pictures you want, are brackets above is a bookmark, defined in this document with the name ckets. Access will replace each bookmark with data from a record in its

At 1,4″ Ln 5 Col 11 PEC TRK EXT OVR English (U,5 Q3C

At 1,4″ Ln 5 Col 11 PEC TRK EXT OVR English (U,5 Q3C

Creating the Access form

For this example, I create a simple form that’s bound to a table named Customers, with the usual name and address fields that you’d expect to find in such a table. Figure 14-8 shows a sample form in Form view. The controls that are relevant to the form letter start at the one containing the name Tori. Starting at that field, and reading down and to the right, the names of the controls are:

FirstName

LastName

Company

Address1

Address2

City

State

In the VBA code to follow, you’ll see them referred to with square brackets — [FirstName], [LastName], [Company], and so forth. The e-mail address control, near the bottom, isn’t really relevant to the topic at hand. The dropdown list near the top of the control provides the user with a means of choosing a customer. The Merge to Word Letter button is named MergeBttn.

Figure 14-8:

Create a form to display one customer’s name and address at a time.

Figure 14-8:

Create a form to display one customer’s name and address at a time.

Excel 2007 User Forms Vba

To use the form, a person chooses a name from the Choose a Customer combo box and then clicks the Merge to Word Letter button. That button executes VBA code to open the document template, replaces each bookmark with data from the current record in the form, prints the document, and then closes Word.

Writing the merge code

For this example, I place the code in the form shown in Figure 14-8 by attaching it to the MergeBttn control’s On Click event. The VBA code is shown in its entirety in Listing 14-2.

Listing 14-2: Merge Code

Private Sub MergeBttn_Click()

‘Declare variables for storing strings (text). Dim AddyLineVar, SalutationVar As String

‘Start building AddyLineVar, by dealing with blank ‘LastName and Company fields (allowed in this table). If IsNull([LastName]) Then AddyLineVar = [Company] ‘Just set SalutationVar to generic «Sirs». SalutationVar = «Sirs» Else

AddyLineVar = [FirstName] + » » + [LastName]

‘If the Company isn’t blank, tack that on after name.

If Not IsNull([Company]) Then

AddyLineVar = AddyLineVar + vbCrLf + [Company] End If

‘Salutation will be customer’s first name. SalutationVar = [FirstName] End If

‘Add line break and Addressl

AddyLineVar = AddyLineVar + vbCrLf + [Addressl]

‘If Address2 isn’t null, add line break and Address2 If Not IsNull([Address2]) Then

AddyLineVar = AddyLineVar + vbCrLf + [Address2] End If

‘Tack on line break then City, State Zip. AddyLineVar = AddyLineVar + vbCrLf + [City] + «, » AddyLineVar = AddyLineVar + [State] + » » + [ZIP]

‘Declare an instance of Microsoft Word. Dim Wrd As New Word.Application

Set Wrd = CreateObject(«Word.Application»)

‘Specify the path and name to the Word document. Dim MergeDoc As String

MergeDoc = Application.CurrentProject.Path MergeDoc = MergeDoc + «WordFormLetter.dot»

‘Open the document template, make it visible. Wrd.Documents.Add MergeDoc Wrd.Visible = True

‘Replace each bookmark with current data. With Wrd.ActiveDocument.Bookmarks

.Item(«TodaysDate»).Range.Text = Date .Item(«AddressLines»).Range.Text = AddyLineVar .Item(«Salutation»).Range.Text = SalutationVar End With

‘Letter is ready to print, so print it. ‘Wrd.ActiveDocument.PrintOut

‘All done. Close up (no need to save document) Wrd.ActiveDocument.Close wdDoNotSaveChanges Wrd.Quit

End Sub

Like all procedures, this one is just a series of small steps carried out in a specific order to achieve some goal. The first line tells you that this procedure will execute any time a user clicks the MergeBttn button.

Private Sub MergeBttn_Click()

The next two lines declare two string variables named AddyLineVar and SalutationVar. Each of those variables will become a string of text to be substituted into the document template in place of the AddressLines and Salutation bookmarks:

‘Declare variables for storing strings (text). Dim AddyLineVar, SalutationVar As String

In the Customers table I use for this example, the Addressl, City, State, and ZIP code fields are required, but the user can leave the FirstName, Company, and Address2 fields empty (Null). The code that follows builds the variable AddyLineVar as needed for whatever information is available in the current record. The first big If…End If block, shown next, starts out by saying, If the LastName field for this record is empty, make the first line of the AddyLineVar the company name and make SalutationVar into the general title, Sirs:.

‘Start building AddyLineVar, by dealing with blank ‘LastName and Company fields (allowed in this table). If IsNull([LastName]) Then AddyLineVar = [Company] ‘Just set SalutationVar to generic «Sirs». SalutationVar = «Sirs»

If the LastName field for this record is not null, the following code adds the customer’s first and last names to AddyLineVar. Note that vbCrLf is the Access VBA constant for a carriage return/linefeed. Each vbCrLf in AddyLineVar translates to the end of the line in the Word document. Note, too, that SalutationVar gets its value from the FirstName field in the following code:

Else

AddyLineVar = [FirstName] + » » + [LastName]

‘If the Company isn’t blank, tack that on after name. If Not IsNull([Company]) Then

AddyLineVar = AddyLineVar + vbCrLf + [Company] End If

‘Salutation will be customer’s first name. SalutationVar = [FirstName] End If

Because Addressl is a required field, you can assume that it is not null. The following code adds a vbCrLf and the contents of the Addressl field to AddyLineVar:

‘Add CRLF and Addressl

AddyLineVar = AddyLineVar + vbCrLf + [Addressl]

The next If…End If block adds a line break and the contents of the Address2 field to AddyLineVar but only if the Address2 field isn’t empty:

‘If Address2 isn’t null, add CRLF and Address2 If Not IsNull([Address2]) Then

AddyLineVar = AddyLineVar + vbCrLf + [Address2] End If

Because the City, State, and ZIP fields are required in the Customers table, the next lines of code just add another vbCrLf to AddyLineVar, followed by the City, a comma and blank space (, ), the State, two blank spaces, and then the ZIP:

‘Tack on line break then City, State Zip. AddyLineVar = AddyLineVar + vbCrLf + [City] + «, » AddyLineVar = AddyLineVar + [State] + » » + [ZIP]

At this point in the code, the AddyLineVar and SalutationVar variables both contain the data to be plugged into the form letter. Now you can start writing the code to open Word and replace its bookmarks with some actual data. First, use the standard syntax described earlier in this chapter to declare and open an instance of Microsoft Word:

The VBA editor won’t accept the statements that follow if you haven’t already selected the Microsoft Word Object Library in your References dialog box.

‘Declare an instance of Microsoft Word.

Dim Wrd As New Word.Application

Set Wrd = CreateObject(«Word.Application»)

From this point in the code, the object variable named Wrd refers to an open instance of Microsoft Word (and its entire Application object, which exposes all of Microsoft Word to VBA.)

The next step is to open the document template that contains the bookmarks and text. The syntax for opening a Word document from Access VBA

is objVar .Documents.Add path. The objVar must match the object variable used in the Dim and Set statements (Wrd in this example).

The path must be the complete path to the Word document. In my example, I place the Word document in the same folder as the database MDB file (which makes it easy to find). In Access, you can use Application. CurrentProject.Path to get the path to the currently open database. I name my Word document WordFormLetter.dot. The following statements create a string variable named MergeDoc that contains the full path and filename of that Word document template:

‘Specify the path and name to the Word document. Dim MergeDoc As String

MergeDoc = Application.CurrentProject.Path MergeDoc = MergeDoc + «WordFormLetter.dot»

If WordFormLetter.dot were in some other folder, I couldn’t use Application.CurrentProject.Path to get its path. I’d have to specify the path literally in the code. For example, in Windows XP, if your user account name is Bobo, and your form letter is named MyFormLetter. dot and is stored in your My Documents folder, the following statement will work just fine provided that you type it into the Code window as one long line.

Wrd.Documents.Add «C:Documents and SettingsBoboMy DocumentsMyFormLetter.dot»

Normally, when VBA opens an instance of Word, the program window is invisible, and all activity takes place behind the scenes. For testing and debugging purposes, though, you’ll probably want to make Word visible so you can see what’s happening. To make the window visible, set its Visible property to True, as shown here:

Wrd.Visible = True

When Word and a document are both open, VBA can refer to the document as objVar .ActiveDocument (where, once again, objVar matches the object variable name, which is Wrd in this example). The ActiveDocument object, in turn, contains a Bookmarks collection, which contains a list of all the bookmarks in the document.

The following statement begins a With…End With block that defines the current document’s Bookmarks collection (Wrd.ActiveDocument.Bookmarks) as the item to which all properties to follow (up to End With) will be applied:

‘Replace each bookmark with current data. With Wrd.ActiveDocument.Bookmarks

Within the With…End With block, you can refer to any bookmark by name by using the syntax .ItemibookmarkName) where bookmarkName is the name of the bookmark as defined in the Word document. Each bookmark has a .Range property, which refers to everything that’s contained within the bookmark. The .Range property in turn has a .Text property, which refers specifically to the text within the bookmark. Thus, the statement

.Item(«Addressl_ines»).Range.Text = AddyLineVar says, Change whatever text is currently in the bookmark named AddressLines to whatever is currently in the variable named AddyLineVar.

In the following code, I change the TodaysDate bookmark to the current date, the AddressLines bookmark to the contents of the AddyLineVar variable, and the Salutation bookmark to whatever is in the variable named

SalutationVar:

.Item(

«TodaysDate»)

.Range.Text =

Date

.Item(

«AddressLines

«).Range.Text

= AddyLineVar

.Item(

«Salutation»)

.Range.Text =

SalutationVar

End With

Onscreen, the document template now contains the complete form letter with all the right information. This next statement prints the form letter:

‘Print the letter. Wrd.ActiveDocument.PrintOut

The following statement closes the letter without saving it. (There’s no need to save the letter after it’s printed because you’ll always have the document template to work with.)

‘All done. Close up (no need to save document) Wrd.ActiveDocument.Close wdDoNotSaveChanges

These two lines close Microsoft Word and end the procedure:

Wrd.Quit End Sub

Figure 14-9 shows an example of using the procedure. There I chose a customer named Tori Pines from the Access form and then clicked the Merge to Word Letter button. The form letter that you see in the background is the result, with the date, address lines, and salutation all in place. The code is written to actually print the letter, so you’d never actually see the form on top of the Word document. (I had to superimpose the form there.) However, you would get a printed copy of the letter shown in the figure.

Figure 14-9:

Record from the form merged into a form letter.

Figure 14-9 shows an example of using the procedure. There I chose a customer named Tori Pines from the Access form and then clicked the Merge to Word Letter button. The form letter that you see in the background is the result, with the date, address lines, and salutation all in place. The code is written to actually print the letter, so you’d never actually see the form on top of the Word document. (I had to superimpose the form there.) However, you would get a printed copy of the letter shown in the figure.

Continue reading here: Interacting with Microsoft Excel

Was this article helpful?

Danny


  • #1

Is it possible to take the data from Access, and merge it into just one Word
document? I wish to create a form letter addressed to one person, using the
data that I have stored in an Access database. However, the only options I
have discovered so far are to either create a mass-mailing, or to create a
poorly formatted report in Access, then use the «publish it» function. This
outputs again a poorly formatted document.

Is it possible for me to design a form letter in Word, and have it pull the
data for just one letter, rather than 100?

Advertisements

Doug Robbins — Word MVP


cjg.groups


  • #3

The solution depends on what level of automation that you need.

In Word 2003, you can use Tools > Letters/Mailings > Mail Merge, and
after selecting the Access table in step 3, check only the one
recipient that you want.

You may also try Albert Kallal’s «MergeSingleWord».
http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html

I automated the process with Visual Basic code to merge the current
record being displayed on an Access form. The form has fields to find
and identify the desired record, a command button to launch this code,
and a text box bound the data table primary key called OrderID.

This article was used as a foundation:
http://support.microsoft.com/?id=209976
The code requires reference (Tools > References) to Word 11 Object
Library; may need to browse for C:PFMS OfficeOffice11msword.olb

The Word template should not be bound to a data source. Bind it to a
data source only to easily enter the merge fields, then convert it back
to a normal Word document (Word 2000: Mail Merge Helper > 1 > Restore
to normal Word document. Word 2003: Mail merge toolbar > Main document
setup > Normal Word document).

You may get errors from Word such as the «Data Link» window or
complaints that Access is locked and needs an admin password. Post
them to this thread.

Here is the code. Any MVPs and pros, feel free to correct. Sorry for
line wrapping; not sure why it does that.

Function OutputDoc()

Dim appWord As Word.Application
Dim objWord As Word.Document

Set appWord = New Word.Application
Set objWord = appWord.Documents.Open(«C:MergeTemplate.doc»)

‘ Make Word visible.
appWord.Visible = True
‘ Set the mail merge data source as the database. Note the query
parameter.
objWord.MailMerge.OpenDataSource Name:=»Database.mdb»,
LinkToSource:=True, Connection:=»TABLE tblData», SQLStatement:=»SELECT
* FROM [tblData] WHERE [Orders.OrderID] = » & Forms!OrderForm!OrderID
‘ Execute the mail merge.
objWord.MailMerge.Destination = wdSendToNewDocument
objWord.MailMerge.Execute

‘ clean up and close Word, closing windows in reverse order that
they were opened
Set objWord = appWord.Documents(«Form Letters1»)
objWord.Close wdDoNotSaveChanges
Set objWord = appWord.Documents(«Sampling Request Form — merge.doc»)
objWord.SaveAs («C:Output.doc»)
appWord.Quit
Set appWord = Nothing
End Function

Good luck.

Access101


  • #4

You guys look like you know what you’re talking about — slick tools. Maybe
you know this one too:

In my Main Merge doc I have:
<<fname>>
<<fname>>

In the Data doc I have column heading and two names
fname
Bill
Mike

When I merge, Bill, of course, replaces each <<fname>> with Bill and looks
like this:
Bill
Bill
What I want, is this:
Bill
Mike

Is this possible?

Any help is appreciated.

The solution depends on what level of automation that you need.

In Word 2003, you can use Tools > Letters/Mailings > Mail Merge, and
after selecting the Access table in step 3, check only the one
recipient that you want.

You may also try Albert Kallal’s «MergeSingleWord».
http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html

I automated the process with Visual Basic code to merge the current
record being displayed on an Access form. The form has fields to find
and identify the desired record, a command button to launch this code,
and a text box bound the data table primary key called OrderID.

This article was used as a foundation:
http://support.microsoft.com/?id=209976
The code requires reference (Tools > References) to Word 11 Object
Library; may need to browse for C:PFMS OfficeOffice11msword.olb

The Word template should not be bound to a data source. Bind it to a
data source only to easily enter the merge fields, then convert it back
to a normal Word document (Word 2000: Mail Merge Helper > 1 > Restore
to normal Word document. Word 2003: Mail merge toolbar > Main document
setup > Normal Word document).

You may get errors from Word such as the «Data Link» window or
complaints that Access is locked and needs an admin password. Post
them to this thread.

Here is the code. Any MVPs and pros, feel free to correct. Sorry for
line wrapping; not sure why it does that.

Function OutputDoc()

Dim appWord As Word.Application
Dim objWord As Word.Document

Set appWord = New Word.Application
Set objWord = appWord.Documents.Open(«C:MergeTemplate.doc»)

‘ Make Word visible.
appWord.Visible = True
‘ Set the mail merge data source as the database. Note the query
parameter.
objWord.MailMerge.OpenDataSource Name:=»Database.mdb»,
LinkToSource:=True, Connection:=»TABLE tblData», SQLStatement:=»SELECT
* FROM [tblData] WHERE [Orders.OrderID] = » & Forms!OrderForm!OrderID
‘ Execute the mail merge.
objWord.MailMerge.Destination = wdSendToNewDocument
objWord.MailMerge.Execute

‘ clean up and close Word, closing windows in reverse order that
they were opened
Set objWord = appWord.Documents(«Form Letters1»)
objWord.Close wdDoNotSaveChanges
Set objWord = appWord.Documents(«Sampling Request Form — merge.doc»)
objWord.SaveAs («C:Output.doc»)
appWord.Quit
Set appWord = Nothing
End Function

Good luck.

Is it possible to take the data from Access, and merge it into just one Word
document? I wish to create a form letter addressed to one person, using the
data that I have stored in an Access database. However, the only options I
have discovered so far are to either create a mass-mailing, or to create a
poorly formatted report in Access, then use the «publish it» function. This
outputs again a poorly formatted document.

Is it possible for me to design a form letter in Word, and have it pull the
data for just one letter, rather than 100?

Doug Robbins — Word MVP


  • #5

See response to your latter post.


Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins — Word MVP

Access101 said:

You guys look like you know what you’re talking about — slick tools.
Maybe
you know this one too:

In my Main Merge doc I have:
<<fname>>
<<fname>>

In the Data doc I have column heading and two names
fname
Bill
Mike

When I merge, Bill, of course, replaces each <<fname>> with Bill and looks
like this:
Bill
Bill
What I want, is this:
Bill
Mike

Is this possible?

Any help is appreciated.

The solution depends on what level of automation that you need.

In Word 2003, you can use Tools > Letters/Mailings > Mail Merge, and
after selecting the Access table in step 3, check only the one
recipient that you want.

You may also try Albert Kallal’s «MergeSingleWord».
http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html

I automated the process with Visual Basic code to merge the current
record being displayed on an Access form. The form has fields to find
and identify the desired record, a command button to launch this code,
and a text box bound the data table primary key called OrderID.

This article was used as a foundation:
http://support.microsoft.com/?id=209976
The code requires reference (Tools > References) to Word 11 Object
Library; may need to browse for C:PFMS OfficeOffice11msword.olb

The Word template should not be bound to a data source. Bind it to a
data source only to easily enter the merge fields, then convert it back
to a normal Word document (Word 2000: Mail Merge Helper > 1 > Restore
to normal Word document. Word 2003: Mail merge toolbar > Main document
setup > Normal Word document).

You may get errors from Word such as the «Data Link» window or
complaints that Access is locked and needs an admin password. Post
them to this thread.

Here is the code. Any MVPs and pros, feel free to correct. Sorry for
line wrapping; not sure why it does that.

Function OutputDoc()

Dim appWord As Word.Application
Dim objWord As Word.Document

Set appWord = New Word.Application
Set objWord = appWord.Documents.Open(«C:MergeTemplate.doc»)

‘ Make Word visible.
appWord.Visible = True
‘ Set the mail merge data source as the database. Note the query
parameter.
objWord.MailMerge.OpenDataSource Name:=»Database.mdb»,
LinkToSource:=True, Connection:=»TABLE tblData», SQLStatement:=»SELECT
* FROM [tblData] WHERE [Orders.OrderID] = » & Forms!OrderForm!OrderID
‘ Execute the mail merge.
objWord.MailMerge.Destination = wdSendToNewDocument
objWord.MailMerge.Execute

‘ clean up and close Word, closing windows in reverse order that
they were opened
Set objWord = appWord.Documents(«Form Letters1»)
objWord.Close wdDoNotSaveChanges
Set objWord = appWord.Documents(«Sampling Request Form — merge.doc»)
objWord.SaveAs («C:Output.doc»)
appWord.Quit
Set appWord = Nothing
End Function

Good luck.

Is it possible to take the data from Access, and merge it into just one
Word
document? I wish to create a form letter addressed to one person, using
the
data that I have stored in an Access database. However, the only
options I
have discovered so far are to either create a mass-mailing, or to
create a
poorly formatted report in Access, then use the «publish it» function.
This
outputs again a poorly formatted document.

Is it possible for me to design a form letter in Word, and have it pull
the
data for just one letter, rather than 100?

Danny


  • #6

Very complete suggestions. You’ve got me past my roadblock, and I’m much
appreciative. Thank you so much!

The solution depends on what level of automation that you need.

In Word 2003, you can use Tools > Letters/Mailings > Mail Merge, and
after selecting the Access table in step 3, check only the one
recipient that you want.

You may also try Albert Kallal’s «MergeSingleWord».
http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html

I automated the process with Visual Basic code to merge the current
record being displayed on an Access form. The form has fields to find
and identify the desired record, a command button to launch this code,
and a text box bound the data table primary key called OrderID.

This article was used as a foundation:
http://support.microsoft.com/?id=209976
The code requires reference (Tools > References) to Word 11 Object
Library; may need to browse for C:PFMS OfficeOffice11msword.olb

The Word template should not be bound to a data source. Bind it to a
data source only to easily enter the merge fields, then convert it back
to a normal Word document (Word 2000: Mail Merge Helper > 1 > Restore
to normal Word document. Word 2003: Mail merge toolbar > Main document
setup > Normal Word document).

You may get errors from Word such as the «Data Link» window or
complaints that Access is locked and needs an admin password. Post
them to this thread.

Here is the code. Any MVPs and pros, feel free to correct. Sorry for
line wrapping; not sure why it does that.

Function OutputDoc()

Dim appWord As Word.Application
Dim objWord As Word.Document

Set appWord = New Word.Application
Set objWord = appWord.Documents.Open(«C:MergeTemplate.doc»)

‘ Make Word visible.
appWord.Visible = True
‘ Set the mail merge data source as the database. Note the query
parameter.
objWord.MailMerge.OpenDataSource Name:=»Database.mdb»,
LinkToSource:=True, Connection:=»TABLE tblData», SQLStatement:=»SELECT
* FROM [tblData] WHERE [Orders.OrderID] = » & Forms!OrderForm!OrderID
‘ Execute the mail merge.
objWord.MailMerge.Destination = wdSendToNewDocument
objWord.MailMerge.Execute

‘ clean up and close Word, closing windows in reverse order that
they were opened
Set objWord = appWord.Documents(«Form Letters1»)
objWord.Close wdDoNotSaveChanges
Set objWord = appWord.Documents(«Sampling Request Form — merge.doc»)
objWord.SaveAs («C:Output.doc»)
appWord.Quit
Set appWord = Nothing
End Function

Good luck.

Is it possible to take the data from Access, and merge it into just one Word
document? I wish to create a form letter addressed to one person, using the
data that I have stored in an Access database. However, the only options I
have discovered so far are to either create a mass-mailing, or to create a
poorly formatted report in Access, then use the «publish it» function. This
outputs again a poorly formatted document.

Is it possible for me to design a form letter in Word, and have it pull the
data for just one letter, rather than 100?

Advertisements

Michael


  • #7

Dear all, I have a similar problem with mail merge. I have a .doc document
and a data source from an oracle database which stores HTML data as text. The
front end application has no problem recognizing the HTML tags and would
display the HTML texts correctly. But once I tried to mail merge this HTML
text to the Word document, Word would show the HTML tags as is. i.e.
<BR>test</BR> instead of a line break before ‘test’, a &amp instead of &, and
a <B>bold</B> instead of a bolded ‘bold’ text.

I wonder if there’s a way to make Word interpret the HTML tags automatically
during the mail merge?

Thanks in advance,
Michael

The solution depends on what level of automation that you need.

In Word 2003, you can use Tools > Letters/Mailings > Mail Merge, and
after selecting the Access table in step 3, check only the one
recipient that you want.

You may also try Albert Kallal’s «MergeSingleWord».
http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html

I automated the process with Visual Basic code to merge the current
record being displayed on an Access form. The form has fields to find
and identify the desired record, a command button to launch this code,
and a text box bound the data table primary key called OrderID.

This article was used as a foundation:
http://support.microsoft.com/?id=209976
The code requires reference (Tools > References) to Word 11 Object
Library; may need to browse for C:PFMS OfficeOffice11msword.olb

The Word template should not be bound to a data source. Bind it to a
data source only to easily enter the merge fields, then convert it back
to a normal Word document (Word 2000: Mail Merge Helper > 1 > Restore
to normal Word document. Word 2003: Mail merge toolbar > Main document
setup > Normal Word document).

You may get errors from Word such as the «Data Link» window or
complaints that Access is locked and needs an admin password. Post
them to this thread.

Here is the code. Any MVPs and pros, feel free to correct. Sorry for
line wrapping; not sure why it does that.

Function OutputDoc()

Dim appWord As Word.Application
Dim objWord As Word.Document

Set appWord = New Word.Application
Set objWord = appWord.Documents.Open(«C:MergeTemplate.doc»)

‘ Make Word visible.
appWord.Visible = True
‘ Set the mail merge data source as the database. Note the query
parameter.
objWord.MailMerge.OpenDataSource Name:=»Database.mdb»,
LinkToSource:=True, Connection:=»TABLE tblData», SQLStatement:=»SELECT
* FROM [tblData] WHERE [Orders.OrderID] = » & Forms!OrderForm!OrderID
‘ Execute the mail merge.
objWord.MailMerge.Destination = wdSendToNewDocument
objWord.MailMerge.Execute

‘ clean up and close Word, closing windows in reverse order that
they were opened
Set objWord = appWord.Documents(«Form Letters1»)
objWord.Close wdDoNotSaveChanges
Set objWord = appWord.Documents(«Sampling Request Form — merge.doc»)
objWord.SaveAs («C:Output.doc»)
appWord.Quit
Set appWord = Nothing
End Function

Good luck.

Is it possible to take the data from Access, and merge it into just one Word
document? I wish to create a form letter addressed to one person, using the
data that I have stored in an Access database. However, the only options I
have discovered so far are to either create a mass-mailing, or to create a
poorly formatted report in Access, then use the «publish it» function. This
outputs again a poorly formatted document.

Is it possible for me to design a form letter in Word, and have it pull the
data for just one letter, rather than 100?

Peter Jamieson


  • #8

Michael — I have responsed (but not with the answer you seek) to your later
similar question.

Peter Jamieson

Michael said:

Dear all, I have a similar problem with mail merge. I have a .doc document
and a data source from an oracle database which stores HTML data as text.
The
front end application has no problem recognizing the HTML tags and would
display the HTML texts correctly. But once I tried to mail merge this HTML
text to the Word document, Word would show the HTML tags as is. i.e.
<BR>test</BR> instead of a line break before ‘test’, a &amp instead of &,
and
a <B>bold</B> instead of a bolded ‘bold’ text.

I wonder if there’s a way to make Word interpret the HTML tags
automatically
during the mail merge?

Thanks in advance,
Michael

The solution depends on what level of automation that you need.

In Word 2003, you can use Tools > Letters/Mailings > Mail Merge, and
after selecting the Access table in step 3, check only the one
recipient that you want.

You may also try Albert Kallal’s «MergeSingleWord».
http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html

I automated the process with Visual Basic code to merge the current
record being displayed on an Access form. The form has fields to find
and identify the desired record, a command button to launch this code,
and a text box bound the data table primary key called OrderID.

This article was used as a foundation:
http://support.microsoft.com/?id=209976
The code requires reference (Tools > References) to Word 11 Object
Library; may need to browse for C:PFMS OfficeOffice11msword.olb

The Word template should not be bound to a data source. Bind it to a
data source only to easily enter the merge fields, then convert it back
to a normal Word document (Word 2000: Mail Merge Helper > 1 > Restore
to normal Word document. Word 2003: Mail merge toolbar > Main document
setup > Normal Word document).

You may get errors from Word such as the «Data Link» window or
complaints that Access is locked and needs an admin password. Post
them to this thread.

Here is the code. Any MVPs and pros, feel free to correct. Sorry for
line wrapping; not sure why it does that.

Function OutputDoc()

Dim appWord As Word.Application
Dim objWord As Word.Document

Set appWord = New Word.Application
Set objWord = appWord.Documents.Open(«C:MergeTemplate.doc»)

‘ Make Word visible.
appWord.Visible = True
‘ Set the mail merge data source as the database. Note the query
parameter.
objWord.MailMerge.OpenDataSource Name:=»Database.mdb»,
LinkToSource:=True, Connection:=»TABLE tblData», SQLStatement:=»SELECT
* FROM [tblData] WHERE [Orders.OrderID] = » & Forms!OrderForm!OrderID
‘ Execute the mail merge.
objWord.MailMerge.Destination = wdSendToNewDocument
objWord.MailMerge.Execute

‘ clean up and close Word, closing windows in reverse order that
they were opened
Set objWord = appWord.Documents(«Form Letters1»)
objWord.Close wdDoNotSaveChanges
Set objWord = appWord.Documents(«Sampling Request Form — merge.doc»)
objWord.SaveAs («C:Output.doc»)
appWord.Quit
Set appWord = Nothing
End Function

Good luck.

Is it possible to take the data from Access, and merge it into just one
Word
document? I wish to create a form letter addressed to one person, using
the
data that I have stored in an Access database. However, the only
options I
have discovered so far are to either create a mass-mailing, or to
create a
poorly formatted report in Access, then use the «publish it» function.
This
outputs again a poorly formatted document.

Is it possible for me to design a form letter in Word, and have it pull
the
data for just one letter, rather than 100?

GaryNSHC


  • #9

I am using this piece of code and am having a little problem with my
mergefields not picking up the correct value for a YES/NO field.

If I use {mergefield name =»false» …} it doesn’t work with single records
but does when I use all records.

BUT ..

When I use {mergefield name = «0» ..} it works for single records but not
for all records.

Whichever way I go, I can’t seem to get the word template to pay ball
correctly whether I use a single record or merge all records.

Has anyone else come across this, and if so, how was it resolved?

Regards

Gary

Graham Mayor


  • #10

What exactly does {Mergefield name} produce when inserted without a
condition?


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor — Word MVP

<>>< ><<> ><<> <>>< ><<> <>>< <>><<>

GaryNSHC


  • #11

My apologies, I am using an IF condition as well as a MERGEFIELD.

The one which works in a single record is:
{IF {mergefield MAACTeam} = «0», «No», «Yes»} and I get «NO»
if I change = «0» to either = «TRUE» or = «FALSE» I get «YES» which is
incorrect.

The one which works for all records is:
{IF {mergefield MAACTeam} = «FALSE», «No», «Yes»} I get either «YES» or «NO»
if I change = «FALSE» to either = «0» or = «-1» I get «YES» for all records
which is incorrect.

If I have just:
{mergefield MAACTeam} I get either «0» or «-1» depending on whether it
should be «YES» or «NO».

Hope this clarifies the problem being encountered.

Regards

Gary

Advertisements

Peter Jamieson


  • #12

If I have just:

{mergefield MAACTeam} I get either «0» or «-1» depending on whether it
should be «YES» or «NO».

Is this actually -1 for Yes and 0 for No (in which case are you using Word
2000 or earlier and/or connecting using DDE? AFAIK the values Word receives
are as follows:

Connection method «Yes» «No»
DDE -1 0
ODBC 0 1
OLE DB True False

When you say «works for a single record» what are you doing differently? Do
you mean you are connecting to a different data source that only has one
record, are you using the same table/query as the data source in both merges
and changing the query criteria for one of them? Or what? Also, are the
Yes/No results for just

{ mergefield MAACTeam }

always -1 and 0, or do they actually differ depending on whehter you are
doing 1 record or many records?

Also, are you really using «FALSE» rather than «False»? Can we assume that
you have not got commas in your IF field? Do you have a bookmark called
False in your Mail Merge Main Document or any included file? Does it make
any difference if you quote the mergefield, e.g.

{ IF «{ MERGEFIELD MAACTeam }» = «0» «No» «Yes» }

Peter Jamieson

GaryNSHC


  • #13

Peter,

As far as I know:

I believe it is Word 2000, and again my apologies, there is no comma between
the values (hangover from coding excel IF statement).

I think the data source is exported as a file (merge.888) which is then used
to create the merge document. I don’t think it is directly linked with Access.

The values are always -1 or 0 depending on what the source data in access
is, depending on whether I am trying to merge one record or all records. I
have about 15 access fields with «Yes» or «No» answers which are being
merged. The fields indicate what activities the person participates in within
our organisation.

I’ll try quoting the meregfield and see if it makes a difference.

Thanks for trying to sort this out for me.

Regards

Gary

Peter Jamieson


  • #14

I can just about see circumstances in which this might occur, but the case
isn’t particularly convincing, which suggests that the explanation is likely
to be staring us in the face :) I gather you’re working at a distance from
the problem so it may be difficult to check stuff and experiment.

It seems to me that whatever may be in the Access file or intermediate file,
Word will only compare correctly with «0» if the YesNo value /it reads/ is
«0», and will only compare correctly with «False» if the values it actually
sees are «False» and «True». Which isn’t what you actually say, but I wonder
whether that is actually the case.

As far as I know, if Word is getting its data from a text file, the only way
it would see -1 as «True» is if
a. it’s opening the file using OLE DB (i.e. it’s Word 2002 or later)
b. there’s a SCHEMA.INI file in the same folder as the text file that
specifies that the column has type «Bit». This could well be the case
because when you export from Access, Access does create such entries in a
SCHEMA.INI — at least sometimes. If someone is using an Access module or
macro to export, then it may also specify a particular export layout.

However, the hypothesis also has to explain why you see -1/0 when you have a
data source with 1 record, but True/False when it has many records.
Possibilities include
a. Word is opening the file using OLE DB but only recognises that the
column is «Yes/No» type (and provides True/False instead of -1/0 when there
are more than so many records in the file — perhaps 8 or 25. I don’t see
this here.
b. Access sets up a SCHEMA.INI entry when it exports multiple records, but
not a single record. (In fact, Access itself does not appear to make this
distinction, although if the export is being done through code, perhaps
something else is doing something differently. What I see is bizarre: when
you export manually, if you specify a file extension (e.g. .txt) Access just
exports the data and modifes SCHEMA.INI. If you do not, Access takes you
through the export layout dialog and /does not/ modify SCHEMA.INI)
c. Word tries to connect to the one-row data files using OLE DB (the
defaul) but fails and falls back to using its Text converter. With the
multi-row files, it succeeds. This is an unlikely way around.

Even if the right explanation is in there somewhere, there’s the question of
what you do about it and how to find out exactly what’s going. What I would
probably prefer to do is avoid the problem altoggether by trying to export
the data using the string values «Y» and «N» instead of numeric/boolean
values. If I had to determine connection method etc., I’d probably use Word
VBA to find the values of ActiveDocument.MailMerge.DataSource.COnnectString,
..QueryString and .Type /after/ the connection had been made.

Best I can right now…

Peter Jamieson

GaryNSHC


  • #15

Peter,

However, the hypothesis also has to explain why you see -1/0 when you have a
data source with 1 record, but True/False when it has many records.

Just to clarify, depending on whether the field condition is «0» or «false»,
and depending on whether 1 record or all records are merged, one merge will
merge fields correctly, whilst the other merge will merge all fields with one
value — whether it is the right or wrong value.

Your technical knowledge is way beyond my comprehension unfortunately. I
will try some of your suggestions from your first resposne to see if that
makes a difference.

Regards

Gary

GaryNSHC


  • #16

Hi all,

Whilst probably not the most elegant solution, what I have found that works
is a «double if» function which checks whether the value is «0» first, if so
then it will display «No», if the value is not «0», a second if function will
determine if the value is «false» and display «No», otherwise it will display
«Yes».

Regards

Gary

Advertisements

Peter Jamieson


  • #17

Looks like you have found a solution but if you can send samples I would be
happy to have a look at them — you would need to remove «KillmapS» from my
email address.

Peter Jamieson

Понравилась статья? Поделить с друзьями:
  • Merging files in excel
  • Merging file in excel
  • Merging documents in word
  • Merging columns in excel
  • Merging cells in excel vba