How To Automate Word from Visual Basic to Create a Mail Merge for Mailing Labels (258512)



The information in this article applies to:

  • Microsoft Office Word 2003
  • Microsoft Word 2002
  • Microsoft Word 2000
  • Microsoft Word 97 for Windows
  • Microsoft Visual Basic Professional Edition for Windows 6.0
  • Microsoft Visual Basic Professional Edition for Windows 5.0

This article was previously published under Q258512

SUMMARY

This article illustrates how you can automate Microsoft Word from a Microsoft Visual Basic application to create and execute a mail merge for mailing labels.

MORE INFORMATION

The sample code in this article uses a tab-delimited text file for the data source. The text file has five fields: Contact_Name, Address, City, Postal_Code, and Country. You can use any text editor (such as Notepad) to create the text file data source.

When you create the data source, remember to separate the fields (columns) with a tab character and separate the records (rows) with a carriage return. The following is an example of how the text file might appear:
Contact_Name	Address	          City	     Postal_Code      Country
Maria Anders	Obere Str. 57	 Berlin	     12209	    Germany  
Thomas Hardy	120 Hanover Sq.	 London	     WA1 1DP	    UK
Hanna Moos	Forsterstr. 57	 Mannheim     68306	    Germany
Laurence Lebihan  12, rue des Bouchers Marseille   13008	    France

				
NOTE: You can use any other data source, such as a Microsoft Access database, instead of the tab-delimited text file.

Step-by-Step Example

  1. Start a new Standard EXE project in Visual Basic. Form1 is created by default.
  2. Add a CommandButton to Form1.
  3. Select the Microsoft Word Object Library for the version of Word that you intend to automate, and then click OK.
  4. Copy the following code to the code window of Form1:
    Private Sub Command1_Click()
    
        Dim oApp As Word.Application
        Dim oDoc As Word.Document
        
        'Start a new document in Word
        Set oApp = CreateObject("Word.Application")
        Set oDoc = oApp.Documents.Add
        
        With oDoc.MailMerge
            
            'Insert the mail merge fields temporarily so that
            'you can use the range containing the merge fields as a layout
            'for your labels -- to use this as a layout, you can add it
            'as an AutoText entry.
            With .Fields
                .Add oApp.Selection.Range, "Contact_Name"
                oApp.Selection.TypeParagraph
                .Add oApp.Selection.Range, "Address"
                oApp.Selection.TypeParagraph
                .Add oApp.Selection.Range, "City"
                oApp.Selection.TypeText "  "
                .Add oApp.Selection.Range, "Postal_Code"
                oApp.Selection.TypeText " -- "
                .Add oApp.Selection.Range, "Country"
            End With
            Dim oAutoText As Word.AutoTextEntry
            Set oAutoText = oApp.NormalTemplate.AutoTextEntries.Add("MyLabelLayout", oDoc.Content)
            oDoc.Content.Delete 'Merge fields in document no longer needed now
                                'that the AutoText entry for the label layout
                                'has been added so delete it.
            
            'Set up the mail merge type as mailing labels and use
            'a tab-delimited text file as the data source.
            .MainDocumentType = wdMailingLabels 
            .OpenDataSource Name:="C:\data.txt" 'Specify your data source here
    
            'Create the new document for the labels using the AutoText entry
            'you added -- 5160 is the label number to use for this sample.
            'You can specify the label number you want to use for the output
            'in the Name argument.
            oApp.MailingLabel.CreateNewDocument Name:="5160", Address:="", _
                AutoText:="MyLabelLayout", LaserTray:=wdPrinterManualFeed
    
            'Execute the mail merge to generate the labels.
            .Destination = wdSendToNewDocument
            .Execute
    
            'Delete the AutoText entry you added
            oAutoText.Delete
            
        End With
        
        'Close the original document and make Word visible so that
    
        'the mail merge results are displayed
        oDoc.Close False
        oApp.Visible = True
    
        'Prevent save to Normal template when user exits Word
        oApp.NormalTemplate.Saved = True
        
    End Sub
    					
    The Name argument for the OpenDataSource method in the preceding code references the data source as c:\data.txt. If your data source has a different path or filename, modify this line in the code accordingly.

  5. Press the F5 key to run the program and click Command1. A mailing label document is created with data taken from the given data source.

REFERENCES

For additional information about automating Microsoft Word or creating mail merge documents, click the following article numbers to view the articles in the Microsoft Knowledge Base:

258523 How To Determine Number of Records Before Executing Mail Merge

220607 How To Automate Microsoft Word to Perform Mail Merge from Visual Basic

244219 How To Automate MailMerge in Word 2000 Using Visual J++ (Java)

220911 How To Automate Microsoft Word to Perform a Mail Merge Using Visual C++ and MFC

212034 WD2000: How to Create Mailing Labels Using Mail Merge

209812 WD2000: Mail Merge Macro Fails to Record Label Number


Modification Type:MajorLast Reviewed:3/23/2006
Keywords:kbAutomation kbhowto KB258512