Access vba open word document mail merge
A classic!
To open a Word document and perform a mail merge using VBA, you can follow these steps:
Step 1: Create a new VBA project
- Open the Visual Basic Editor by pressing
Alt + F11
or by navigating toDeveloper
>Visual Basic
in the ribbon. - In the Editor, click
Insert
>Module
to create a new module.
Step 2: Declare the Word application object
-
In the module, declare a variable to hold the Word application object:
Dim wdApp As Object
Step 3: Create a new instance of Word
-
Create a new instance of Word:
Set wdApp = CreateObject("Word.Application")
Step 4: Open the Word document
-
Open the Word document you want to perform the mail merge on:
wdApp.Documents.Open "C:\Path\To\Your\Document.docx"
Replace
C:\Path\To\Your\Document.docx
with the actual path and name of your Word document.
Step 5: Set the mail merge data source
- Set the mail merge data source (e.g., an Excel worksheet):
wdApp.ActiveDocument.MailMerge.OpenDataSource _ "C:\Path\To\Your\Data.xlsx", _ wdMergeDataSourceExcel, _ "Sheet1"
Replace
C:\Path\To\Your\Data.xlsx
with the actual path and name of your data source file, andSheet1
with the name of the worksheet containing the data.
Step 5 (optional): Set the mail merge fields
- If your Word document contains mail merge fields, you can set them using the
MailMerge.OpenDataSource
method:wdApp.ActiveDocument.MailMerge.OpenDataSource _ "C:\Path\To\Your\Data.xlsx", _ wdMergeDataSourceExcel, _ "Sheet1", _ "First Name", _ "Last Name", _ "Email Address"
Replace the field names with the actual names of the fields in your data source.
Step 6: Perform the mail merge
-
Perform the mail merge:
wdApp.ActiveDocument.MailMerge.Execute
Step 7: Close the Word application
-
Close the Word application:
wdApp.Quit
Step 8: Release the Word application object
-
Release the Word application object:
Set wdApp = Nothing
Here's the complete code:
Sub OpenWordDocumentAndPerformMailMerge() Dim wdApp As Object Set wdApp = CreateObject("Word.Application") wdApp.Documents.Open "C:\Path\To\Your\Document.docx" wdApp.ActiveDocument.MailMerge.OpenDataSource _ "C:\Path\To\Your\Data.xlsx", _ wdMergeDataSourceExcel, _ "Sheet1" wdApp.ActiveDocument.MailMerge.Execute wdApp.Quit Set wdApp = Nothing End Sub
Note: Make sure to replace the file paths and names with the actual values for your specific scenario.