Excel 2019 vba mailmerge

A classic!

Mail Merge in Excel VBA is a powerful feature that allows you to automate the process of creating documents with data from an Excel worksheet. Here's a step-by-step guide to help you get started:

Prerequisites:

  1. Excel 2019 (or later) with VBA enabled.
  2. A worksheet with data you want to use for the mail merge.
  3. A document template (e.g., Word document, PDF, or text file) that you want to merge with the data.

Step 1: Create a new VBA project

  1. Open the Visual Basic Editor by pressing Alt + F11 or navigating to Developer > Visual Basic in the ribbon.
  2. In the Visual Basic Editor, click Insert > Module to create a new module.

Step 2: Set up the mail merge

  1. In the module, declare a variable to store the document template:
    Dim doc As Object
  2. Set the document template path and file name:
    doc = CreateObject("Word.Application")
    doc.Documents.Open "C:\Path\To\DocumentTemplate.docx"

    Replace C:\Path\To\DocumentTemplate.docx with the actual path and file name of your document template.

Step 3: Loop through the data

  1. Loop through the rows in your worksheet using a For loop:
    For i = 1 To Range("A1").End(xlDown).Row
     ' Your code here
    Next i

    Replace A1 with the cell reference of the first row of your data.

Step 4: Merge the data

  1. Use the doc.MailMerge object to merge the data with the document template:
    doc.MailMerge.OpenDataSource _
     Source:=Range("A1").CurrentRegion.Address, _
     ConfirmConversions:=False, _
     Format:=wdOpenFormatXML

    This code opens the document template and sets up the mail merge using the data in the current region (i.e., the range of cells from A1 to the last row with data).

Step 5: Save the merged document

  1. Use the doc.SaveAs method to save the merged document:
    doc.SaveAs "C:\Path\To\MergedDocument.docx", wdFormatXMLDocument

    Replace C:\Path\To\MergedDocument.docx with the actual path and file name where you want to save the merged document.

Full code example:

Sub MailMerge()
    Dim doc As Object
    Set doc = CreateObject("Word.Application")
    doc.Documents.Open "C:\Path\To\DocumentTemplate.docx"

    For i = 1 To Range("A1").End(xlDown).Row
        doc.MailMerge.OpenDataSource _
            Source:=Range("A1").CurrentRegion.Address, _
            ConfirmConversions:=False, _
            Format:=wdOpenFormatXML
        doc.MailMerge.Execute
        doc.SaveAs "C:\Path\To\MergedDocument" & i & ".docx", wdFormatXMLDocument
    Next i

    doc.Quit
    Set doc = Nothing
End Sub

Tips and Variations:

I hope this helps you get started with mail merge in Excel VBA!