How to Set Word Mail Merge Output to Save With Custom Filename Pattern
🔍 WiseChecker

How to Set Word Mail Merge Output to Save With Custom Filename Pattern

When you run a mail merge in Word, the default output is a single document with one page per record. Saving each record as a separate file with a custom filename pattern—such as “Invoice_12345_JohnDoe.docx”—requires a few extra steps. Word does not offer a built-in dialog to name merged files automatically. This article explains how to use a Visual Basic for Applications macro to save each merged record with a filename that combines static text and field values from your data source.

Key Takeaways: Saving Mail Merge Output With Custom Filenames

  • Alt+F11 to open the VBA editor: Access the macro environment where you will write the filename automation code.
  • MailMerge.DataSource.DataFields(“FieldName”).Value: VBA syntax to retrieve a specific field value from the current merge record for use in the filename.
  • ActiveDocument.SaveAs2 FileName:=path & filename: Command that saves the current record as a new document with your custom name.

ADVERTISEMENT

How Word Handles Mail Merge Output

By default, Word’s mail merge feature outputs all records into one continuous document. Each record starts on a new page or section break. This single document is fine for printing or emailing as a batch, but it does not create individual files. To save each record as a separate file with a custom filename pattern—for example, combining a record ID with a name—you must automate the process with a macro. The macro loops through each record, extracts field values, builds a filename string, and saves the current record using the SaveAs2 method. Before writing the macro, you must complete the mail merge setup: connect to your data source, insert merge fields into the main document, and preview the results to confirm the fields appear correctly.

Prerequisites for the Macro

Before running the macro, confirm the following items are in place:

  • Your data source (Excel worksheet, Access database, Outlook contacts, or other) is connected to the main document.
  • Merge fields are inserted in the document where you want the custom filename components to appear.
  • You know the exact names of the fields you will use in the filename pattern. Field names are case-sensitive in VBA.
  • You have a destination folder where the new files will be saved. Create the folder if it does not exist.
  • Macro security settings allow you to run VBA code. Set them to Enable all macros temporarily or digitally sign your macro.

ADVERTISEMENT

Steps to Create and Run the Custom Filename Macro

Follow these steps to write a macro that saves each mail merge record with a custom filename pattern.

  1. Open the VBA editor
    Press Alt+F11 in Word to open the Visual Basic for Applications editor. If the editor opens but no project is visible, expand Normal or Project (MailMergeDocument) in the left pane.
  2. Insert a new module
    In the VBA editor, click Insert on the menu bar and select Module. A blank code window appears.
  3. Write the macro code
    Copy and paste the following code into the module window. Replace the placeholder values with your own folder path and field names.
    Sub SaveMergeWithCustomFilename()
        Dim MainDoc As Document
        Dim i As Integer
        Dim FolderPath As String
        Dim FileName As String
        Dim FieldValue1 As String
        Dim FieldValue2 As String
        
        ' Set the destination folder — change this path
        FolderPath = "C:\MailMergeOutput\"
        
        ' Ensure folder path ends with backslash
        If Right(FolderPath, 1) <> "\" Then
            FolderPath = FolderPath & "\"
        End If
        
        Set MainDoc = ActiveDocument
        
        With MainDoc.MailMerge
            .Destination = wdSendToNewDocument
            .SuppressBlankLines = True
            For i = 1 To .DataSource.RecordCount
                .DataSource.FirstRecord = i
                .DataSource.LastRecord = i
                ' Execute merge for the single record
                .Execute Pause:=False
                ' Get field values for filename
                FieldValue1 = .DataSource.DataFields("CustomerID").Value
                FieldValue2 = .DataSource.DataFields("LastName").Value
                ' Build filename — adjust pattern as needed
                FileName = "Invoice_" & FieldValue1 & "_" & FieldValue2 & ".docx"
                ' Save the resulting document
                ActiveDocument.SaveAs2 FileName:=FolderPath & FileName
                ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
            Next i
        End With
        
        Set MainDoc = Nothing
        MsgBox "Merge complete. Files saved to " & FolderPath
    End Sub
    
  4. Adjust field names and filename pattern
    In the code, change CustomerID and LastName to match the actual field names in your data source. Modify the FileName line to match your desired pattern. For example, "Letter_" & FieldValue1 & "_" & FieldValue2 & ".docx" produces filenames like Letter_102_Smith.docx.
  5. Run the macro
    Close the VBA editor and return to Word. Press Alt+F8 to open the Macros dialog. Select SaveMergeWithCustomFilename from the list and click Run. Word processes each record and saves individual files to the specified folder.
  6. Verify the output files
    Open the destination folder. Confirm that each file exists and that the filenames match your pattern. Open a few files to verify the content corresponds to the correct record.

Common Problems and How to Fix Them

“Subscript out of range” error when running the macro

This error occurs when the field name in the macro does not match a field in your data source. Open your data source and note the exact column headers. Update the field names in the macro to match those headers. If your data source uses headers with spaces, enclose the name in square brackets, for example .DataFields("[First Name]").Value.

Files are saved but the content is blank or incomplete

The macro may be executing the merge before the main document is fully connected to the data source. Ensure you have run a test merge to a new document at least once before running the macro. Also confirm that the mail merge main document is the active document when you run the macro.

Macro does not appear in the Macros dialog

The macro will not appear if you placed the code in a document module instead of a standard module. In the VBA editor, right-click the module that contains your code and verify it is listed under Normal or under your document project. If it is under the document project, the macro is available only when that document is open.

Filenames contain invalid characters like colons or slashes

Windows does not allow certain characters in filenames. If your data source contains values with characters such as : / \ ? " < > |, the SaveAs2 method will fail. Add a line in the macro to replace those characters before building the filename. For example: FieldValue1 = Replace(FieldValue1, ":", "").

Mail Merge Output Methods Comparison

Item Default Merge to New Document Macro with Custom Filename Pattern
Output format Single document with all records One file per record
Filename control No control — user saves manually Full control using field values
Setup time None 15–30 minutes for macro creation
Repeatability Manual save each time Run macro for any data source
Error handling User corrects issues manually Requires VBA debugging

You can now save each mail merge record as a separate file with a custom filename pattern using the macro provided. Test the macro with a small data set first to confirm the filename pattern works correctly. For advanced usage, modify the macro to include date stamps, sequential numbers, or conditional logic based on field values. The key to reliable output is matching field names exactly and ensuring the destination folder exists before running the macro.

ADVERTISEMENT