Code Generator | VBA

Automate Mail Merge to Individual PDFs with VBA

This guide details a VBA function that executes a mail merge using Excel data, generating and saving personalized documents as individual PDF files. Streamline your document creation process with automation.


Empty image or helper icon

Prompt

mail merge to saved individual pdf files with excel data range a table name

Answer

Mail Merge to Individual PDF Files using VBA

In this section, we will create a VBA function that performs a mail merge using data from an Excel table and saves the merged documents as individual PDF files. This process helps automate document generation for multiple recipients.

1. Code Overview

The function will perform the following steps:

  • Verify the existence of the specified table and its range.
  • Create a Word document and set up the mail merge.
  • Loop through each record in the data table.
  • Populate the document, then save each completed document as a separate PDF file.

2. Required References

Ensure that the following references are enabled in your VBA environment:

  • Microsoft Word xx.x Object Library (for mail merge functionality)

3. VBA Code Implementation

Sub MailMergeToPDF()
    ' This function performs a mail merge with data from an Excel table and saves the output as individual PDF files.
    
    Dim wdApp As Object
    Dim wdDoc As Object
    Dim ws As Worksheet
    Dim tbl As ListObject
    Dim cell As Range
    Dim pdfFileName As String
    Dim pdfFolder As String
    Dim rowCount As Long
    Dim i As Long

    ' Validate the active sheet and table name
    Set ws = ThisWorkbook.ActiveSheet
    On Error Resume Next
    Set tbl = ws.ListObjects("YourTableName") ' Change "YourTableName" to the name of your table
    On Error GoTo 0
    
    If tbl Is Nothing Then
        MsgBox "Error: Table 'YourTableName' not found.", vbCritical
        Exit Sub
    End If

    ' Set up PDF saving location
    pdfFolder = ThisWorkbook.Path & "\PDFs\"
    If Dir(pdfFolder, vbDirectory) = "" Then
        MkDir pdfFolder  ' Create PDF folder if it doesn't exist
    End If
    
    ' Initialize Word application
    Set wdApp = CreateObject("Word.Application")
    wdApp.Visible = False  ' Keep Word hidden
    
    ' Open the mail merge template
    Set wdDoc = wdApp.Documents.Open("C:\Path\To\Your\MailMergeTemplate.docx") ' Change to your template path
    
    With wdDoc.MailMerge
        ' Set the data source
        .OpenDataSource Name:=ThisWorkbook.FullName, _
                        SQLStatement:="SELECT * FROM `" & tbl.Name & "`"
        
        rowCount = tbl.ListRows.Count
        
        ' Loop through each record and execute mail merge
        For i = 1 To rowCount
            .Destination = 0  ' Creates a new document
            .Execute Pause:=False
            
            ' Construct file name based on a specific field, e.g., Name
            pdfFileName = pdfFolder & tbl.ListRows(i).Range.Cells(1, 1).Value & ".pdf" ' Adjust field as necessary
            
            ' Save the merged document as a PDF
            wdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:=pdfFileName, _
                                                       ExportFormat:=17, _  ' wdExportFormatPDF
                                                       OpenAfterExport:=False, _
                                                       OptimizeFor:=0, _  ' wdExportOptimizeForPrint
                                                       Range:=0, _  ' wdExportAllDocument
                                                       From:=1, _
                                                       To:=1, _
                                                       Item:=0, _
                                                       IncludeDocProps:=True, _
                                                       KeepIRM:=True, _
                                                       CreateBookmarks:=1, _  ' wdExportCreateWordBookmarks
                                                       DocStructureTags:=True
            
            ' Close the newly created document
            wdApp.ActiveDocument.Close False
        Next i
        
    End With
    
    ' Clean up
    wdDoc.Close False
    wdApp.Quit
    
    Set wdDoc = Nothing
    Set wdApp = Nothing
    
    MsgBox "Mail merge completed and PDFs saved in: " & pdfFolder, vbInformation
End Sub

4. Code Explanation

Overview of Code Sections:

  • Imports and Setup: Initializes necessary objects, checks for the table and sets up the folder path for saving PDFs.
  • Mail Merge Processing: Retrieves data from the specified Excel table, iterates through each row, performs the mail merge, and saves each document as a PDF.
  • Cleanup: Closes Word and cleans up the objects to free resources.

5. Usage Example

  1. Prepare an Excel Table:

    • Create a table in Excel named "YourTableName" with columns for names, addresses, and other needed information.
  2. Create a Word Template:

    • Set up a Word document as a template for your mail merge with placeholders for your data fields.
  3. Run the Code:

    • Open your Excel file containing the macro, press ALT + F11 to access VBA, load the code into a Module, and run the MailMergeToPDF subroutine.

6. Conclusion

This VBA code automates the process of mail merging through Word while saving the results as individual PDF files based on Excel data. By following this structured approach, you can efficiently produce numerous personalized documents quickly.

For in-depth learning on data automation and VBA, consider the Enterprise DNA Platform courses.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This guide details a VBA function that executes a mail merge using Excel data, generating and saving personalized documents as individual PDF files. Streamline your document creation process with automation.