Automate Word from Visual Basic to create a mail merge for mailing labels – Office

Microsoft Technical Article






Automating Word Mail Merge for Mailing Labels

🚀 Overview

In many enterprise environments, the manual generation of mailing labels is a repetitive task prone to formatting inconsistencies. This guide provides a technical deep-dive into automating Microsoft Word via Visual Basic to programmatically generate and execute mail merges for mailing labels. By leveraging the Word Object Model, IT administrators can build custom applications that interface with external data sources to produce standardized, print-ready documents with minimal user intervention.

⚙️ Key Technical Details

The automation process relies on the interaction between a Visual Basic “Standard EXE” project and the Microsoft Word Object Library. Below are the core components required for successful implementation:

  • Data Source Preparation: While various databases can be used, this methodology utilizes a tab-delimited text file. This file must be structured with specific headers and record separators. For example:

    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: Each field must be separated by a tab character, and each record must end with a carriage return.

  • Library Referencing: To access the Word API, the project must include a reference to the Microsoft Word Object Library corresponding to the version of Office installed on the host machine.
  • Layout Logic via AutoText: A sophisticated aspect of this automation is the use of AutoTextEntries. The code temporarily creates merge fields in a blank document, captures that layout as an AutoText entry (e.g., "MyLabelLayout"), and then applies that layout to a specific label template (such as the Avery 5160).

💻 Technical Implementation

The following Visual Basic code demonstrates the sequence of starting the Word application, defining the mail merge parameters, and executing the merge.

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 that contains 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 the 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
    

🛡️ Impact

Implementing this automation solution has several significant advantages for IT administrators and organizational workflows:

  • Operational Consistency: By hardcoding label types (e.g., "5160") and field mappings, admins ensure that every label generated by the department meets corporate formatting standards.
  • Reduced Manual Error: Eliminating the “Mail Merge Wizard” steps for end-users prevents common mistakes such as incorrect field mapping or accidental deletion of data source connections.
  • Scalability: This method allows for the rapid generation of thousands of labels. Because the output is directed to a new document (wdSendToNewDocument), users can perform a final quality check before sending the job to a physical printer.
  • Template Integrity: The script includes a safety measure (oApp.NormalTemplate.Saved = True) to prevent programmatic changes from prompting the user to save changes to their global Normal.dotm template, maintaining a clean environment.

Official Source: Read the full article on Microsoft.com