VBA Code
The mail merge object is always available regardless of whether or not the specified document is a mail merge document
If you haven't added an envelope to the active mailmerge document then using any of the following will cause an error address, addressfromleft, addressfromtop, feedsource, returnaddress, returnaddressfromleft, returnaddressfromtop and updatedocument
Type of Document
This checks to make sure the document is not a mail merge document
The State returns the current state of the mail merge operation. Read-only WdMailMergeState.
If ActiveDocument.MailMerge.State = wdMailMergeState.wdNormalDocument Then
End If
This checks to make sure that the document is a main document with an attached data source.
If ActiveDocument.MailMerge.State = wdMailMergeState.wdMainAndDataSource Then
End If
MailMerge Object
Use the MailMerge property to return the MailMerge object.
The MailMerge object is always available regardless of whether the mail merge operation has begun.
Use the State property to determine the status of the mail merge operation.
The following example executes a mail merge if the active document is a main document with an attached data source.
If ActiveDocument.MailMerge.State = wdMailMergeState.wdMainAndDataSource Then
ActiveDocument.MailMerge.Execute
End If
The following example merges the main document with the first three data records in the attached data source and then sends the results to the printer.
Set myMerge = ActiveDocument.MailMerge
If myMerge.State = wdMailMergeState.wdMainAndSourceAndHeader Or _
myMerge.State = wdMailMergeState.wdMainAndDataSource Then
With myMerge.DataSource
.FirstRecord = 1
.LastRecord = 3
End With
End If
With myMerge
.Destination = wdMailMergeDestination.wdSendToPrinter
.Execute
End With
MailMerge.EditMainDocument
Activates the mail merge main document associated with the specified header source or data source document.
Note If the main document isn't open, an error occurs. Use the Open method if the main document isn't currently open.
This example attempts to activate the main document associated with the active data source document. If the main document isn't open, the Open dialog box is displayed, with a message in the status bar.
Sub ActivateMain()
On Error GoTo errorhandler
Documents("Data.doc").MailMerge.EditMainDocument
Exit Sub
errorhandler:
If Err = 4605 Then StatusBar = "Main document is not open"
Dialogs(wdWordDialog.wdDialogFileOpen).Show
End Sub
MailMerge.Execute
Optional Variant. True for Microsoft Word pause and display a troubleshooting dialog box if a mail merge error is found. False to report errors in a new document.
This example executes a mail merge if the active document is a main document with an attached data source.
Set myMerge = ActiveDocument.MailMerge
If myMerge.State = wdMailMergeState.wdMainAndDataSource Then
MyMerge.Execute(Pause:=False)
End If
With ActiveDocument.MailMerge
.Destination = wdMailMergeDestination.wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdMailMergeDefaultRecord.wdDefaultFirstRecord
.LastRecord = wdMailMergeDefaultRecord.wdDefaultLastRecord
End With
.Execute Pause:=False
End With
MailMerge.Check
Simulates the mail merge operation, pausing to report each error as it occurs.
This example checks the active document for mail merge errors.
ActiveDocument.MailMerge.Check
MailMerge.DataSource
Returns a MailMergeDataSource object that refers to the data source attached to a mail merge main document. Read-only.
This example displays the name of the data source attached to the active document.
If ActiveDocument.MailMerge.DataSource.Name <> "" Then _
MsgBox ActiveDocument.MailMerge.DataSource.Name
This example displays the next record from the data source attached to Main.doc.
ActiveDocument.ActiveWindow.View.ShowFieldCodes = False
With Documents("Main.doc").MailMerge
.ViewMailMergeFieldCodes = False
.DataSource.ActiveRecord = wdMailMergeActiveRecord.wdNextRecord
End With
MailMergeDataSource Object
Use the DataSource property to return the MailMergeDataSource object.
The following example displays the name of the data source associated with the active document.
If ActiveDocument.MailMerge.DataSource.Name <> "" Then
MsgBox ActiveDocument.MailMerge.DataSource.Name
End If
The following example displays the field names in the data source associated with the active document.
For Each aField In ActiveDocument.MailMerge.DataSource.FieldNames
MsgBox aField.Name
Next aField
The following example opens the data source associated with Form letter.doc and determines whether the FirstName field includes the name "Kate."
With Documents("Form letter.doc").MailMerge
.EditDataSource
If .DataSource.FindRecord(FindText:="Kate", _
Field:="FirstName") = True Then
MsgBox "Data was found"
End If
End With
MailMerge.EditDataSource
Opens or switches to the mail merge data source.
If the data source is a Word document, this method opens the data source (or activates the data source if it's already open).
If Word is accessing the data through dynamic data exchange (DDE)— using an application such as Microsoft Excel or Microsoft Access - this method displays the data source in that application.
If Word is accessing the data through open database connectivity (ODBC), this method displays the data in a Word document. Note that if Microsoft Query is installed, a message appears, providing the option to display Microsoft Query instead of converting data.
Example
This example opens or activates the data source attached to the document named "Sales.doc."
Documents("Sales.doc").MailMerge.EditDataSource
This example opens or activates the attached data source if the data source is a Word document.
Dim dsMain As MailMergeDataSource
Set dsMain = ActiveDocument.MailMerge.DataSource
If dsMain.Type = wdMailMergeDataSource.wdMergeInfoFromWord Then
ActiveDocument.MailMerge.EditDataSource
End If
MailMerge.OpenDataSource
Attaches a data source to the specified document, which becomes a main document if it's not one already.
ActiveDocument.MailMerge.OpenDataSource Name:= "C:\Temp\mergeSource.csv"
Format:=wdOpenFormat.wdOpenFormatAuto,
ConfirmConversions:=False, _
ReadOnly:=False, _
LinkToSource:=True, _
AddToRecentFiles:=False, _
PasswordDocument:="", _
PasswordTemplate:="", _
Revert:=False, _
WritePasswordDocument:="", _
WritePasswordTemplate:="", _
Connection:="", _
SQLStatement:="", _
SQLStatement1="", _
OpenExclusive:= , _
SubType:=wdMergeSubType.wdMergeSubTypeOther
Name - Required String. The data source file name. You can specify a Microsoft Query (.qry) file instead of specifying a data source, a connection string, and a query string.
Format - Optional Variant. The file converter used to open the document. To specify an external file format, use the OpenFormat property with the FileConverter object to determine the value to use with this argument.
ConfirmConversions - Optional Variant. True to display the Convert File dialog box if the file isn't in Microsoft Word format.
ReadOnly - Optional Variant. True to open the data source on a read-only basis.
LinkToSource - Optional Variant. True to perform the query specified by Connection and SQLStatement each time the main document is opened.
AddToRecentFiles - Optional Variant. True to add the file name to the list of recently used files at the bottom of the File menu.
PasswordDocument - Optional Variant. The password used to open the data source. (See Remarks below.)
PasswordTemplate - Optional Variant. The password used to open the template. (See Remarks below.)
Revert - Optional Variant. Controls what happens if Name is the file name of an open document. True to discard any unsaved changes to the open document and reopen the file; False to activate the open document.
WritePasswordDocument - Optional Variant. The password used to save changes to the document. (See Remarks below.)
WritePasswordTemplate - Optional Variant. The password used to save changes to the template. (See Remarks below.)
Connection - Optional Variant. A range within which the query specified by SQLStatement is to be performed. (See Remarks below.) How you specify the range depends on how data is retrieved. For example:
SQLStatement - Optional Variant. Defines query options for retrieving data. (See Remarks below.)
SQLStatement1 - Optional Variant. If the query string is longer than 255 characters, SQLStatement specifies the first portion of the string, and SQLStatement1 specifies the second portion. (See Remarks below.)
OpenExclusive - Optional Variant. True to open exclusively.
Attaches a table from an Access database (using DDE)
This example creates a new main document and attaches the Orders table from a Microsoft Access database named "Northwind.mdb."
With ActiveDocument.MailMerge
.MainDocumentType = wdMailMergeMainDocType.wdFormLetters
.OpenDataSource Name:="C:\Temp\Northwind.mdb"
LinkToSource:=True, _
AddToRecentFiles:=False, _
Connection:="TABLE Orders"
End With
Attaches a table from an Access database (using ODBC)
This example uses ODBC to attach the Microsoft Access database named "Northwind.mdb" to the active document.
The SQLStatement argument selects the records in the Customers table.
Dim strConnection As String
strConnection = "DSN=MS Access Databases;"DBQ=C:\Northwind.mdb;"FIL=RedISAM;"
With ActiveDocument.MailMerge
.MainDocumentType = wdMailMergeMainDocType.wdFormLetters
.OpenDataSource Name:="C:\Temp\NorthWind.mdb", _
Connection:=strConnection, _
SQLStatement:="SELECT * FROM Customers"
End With
Attaches a named range from an Excel Workbook
This example creates a new main document and attaches the Microsoft Excel spreadsheet named "Names.xls.".
The Connection argument retrieves data from the range named "Sales."
With ActiveDocument.MailMerge
.MainDocumentType = wdMailMergeMainDocType.wdCatalog
.OpenDataSource Name:="C:\Documents\Names.xls", _
ReadOnly:=True, _
Connection:="Sales"
End With
Removing a DataSource
ActiveDocument.MailMerge.MainDocumentType = wdMailMergeMainDocType.wdNotAMergeDocument
MailMerge.CreateDataSource
Creates a Microsoft Word document that uses a table to store data for a mail merge.
The new data source is attached to the specified document, which becomes a main document if it's not one already.
This example creates a new data source document named "Data.doc" and attaches the data source to the active document.
The new data source includes a five-column table that has the field names specified by the HeaderRecord argument.
ActiveDocument.MailMerge.CreateDataSource(Name:="C:\Documents\Data.doc", _
PasswordDocument:=
WritePasswordDocument:=
HeaderRecord:="Name, Address, City, State, Zip"
MSQuery:=
SQLStatement:=
SQLStatement1:=
Connection:=
LinkToSource:=)
Name - Optional Variant. The path and file name for the new data source.
PasswordDocument - Optional Variant. The password required to open the new data source.
WritePasswordDocument - Optional Variant. The password required to save changes to the data source.
HeaderRecord - Optional Variant. Field names for the header record. If this argument is omitted, the standard header record is used: "Title, FirstName, LastName, JobTitle, Company, Address1, Address2, City, State, PostalCode, Country, HomePhone, WorkPhone." To separate field names, use the list separator specified in Regional Settings in Control Panel.
MSQuery - Optional Variant. True to launch Microsoft Query, if it's installed. The Name, PasswordDocument, and HeaderRecord arguments are ignored.
SQLStatement - Optional Variant. Defines query options for retrieving data.
SQLStatement1 - Optional Variant. If the query string is longer than 255 characters, SQLStatement specifies the first portion of the string, and SQLStatement1 specifies the second portion.
Connection - Optional Variant. A range within which the query specified by SQLStatement will be performed. How you specify the range depends on how data is retrieved. When retrieving data through ODBC, you specify a connection string. When retrieving data from Microsoft Excel using DDE, you specify a named range. When retrieving data from Microsoft Access, you specify the word "Table" or "Query" followed by the name of a table or query.
LinkToSource - Optional Variant. True to perform the query specified by Connection and SQLStatement each time the main document is opened.
Types of DataSource
ActiveDocument.MailMerge.DataSource.Type = wdMailMergeDataSource.wdNoMergeInfo
Opening a Linked DataSource
When a mailmerge document is opened you will be asked if you want to link it to its data source.
If the datasource cannot be accessed remotely by another means then it can be accessed directly using the datasource of the document
ActiveDocument.MailMerge.DataSource
List of Field Names
This list can be accessed using the FieldNames collection. This collection starts from 1.
ActiveDocument.MailMerge.DataSource.FieldNames
Dim iFieldCount As Integer
For iFieldCount = 1 to ActiveDocument.MailMerge.DataSource.FieldNames.Count
End If
List of Data Fields
This list can be accessed using the FieldNames collection. This collection starts from 1.
ActiveDocument.MailMerge.DataSource.DataFields
Dim iFieldCount As Integer
For iFieldCount = 1 to ActiveDocument.MailMerge.DataSource.DataFields.Count
End If
ActiveDocument.MailMerge.DataSource.ActiveRecord
ActiveDocument.MailMerge.DataSource.FindRecord
ActiveDocument.MailMerge.DataSource.FirstRecord
ActiveDocument.MailMerge.DataSource.Included
ActiveDocument.MailMerge.DataSource.InvalidAddress
ActiveDocument.MailMerge.DataSource.InvalidComment
ActiveDocument.MailMerge.DataSource.LastRecord
ActiveDocument.MailMerge.DataSource.MappedDataFields
ActiveDocument.MailMerge.DataSource.RecordCount
MailMerge.CreateHeaderSource
Creates a Microsoft Word document that stores a header record that's used in place of the data source header record in a mail merge. This method attaches the new header source to the specified document, which becomes a main document if it's not one already.
Note The new header source uses a table to arrange mail merge field names.
Security Avoid using hard-coded passwords in your applications. If a password is required in a procedure, request the password from the user, store it in a variable, and then use the variable in your code. For recommended best practices on how to do this, see Security Notes for Microsoft Office Solution Developers.
expression.CreateHeaderSource(Name, PasswordDocument, WritePasswordDocument, HeaderRecord)
expression Required. An expression that returns a MailMerge object.
Name Required String. The path and file name for the new header source.
PasswordDocument Optional Variant. The password required to open the new header source.
WritePasswordDocument Optional Variant. The password required to save changes to the new header source.
HeaderRecord Optional Variant. A string that specifies the field names for the header record. If this argument is omitted, the standard header record is used: "Title, FirstName, LastName, JobTitle, Company, Address1, Address2, City, State, PostalCode, Country, HomePhone, WorkPhone." To separate field names in Windows, use the list separator specified in Regional Settings in Control Panel.
This example creates a header source with five field names and attaches the new header source named "Header.doc" to the active document.
ActiveDocument.MailMerge.CreateHeaderSource Name:="Header.doc", _
HeaderRecord:="Name, Address, City, State, Zip"
This example creates a header source for the document named "Main.doc" (with the standard header record) and opens the data source named "Data.doc."
With Documents("Main.doc").MailMerge
.CreateHeaderSource Name:="Fields.doc"
.OpenDataSource Name:="C:\Documents\Data.doc"
End With
MailMerge.EditHeaderSource
Opens the header source attached to a mail merge main document, or activates the header source if it's already open.
Note If the mail merge main document doesn't have a header source, this method causes an error.
This example attaches a header source to the active document and then opens the header source.
With ActiveDocument.MailMerge
.MainDocumentType = wdFormLetters
.OpenHeaderSource Name:="C:\Documents\Header.doc"
.EditHeaderSource
End With
This example opens the header source if the active document has an associated header file attached to it.
Dim mmTemp As MailMerge
Set mmTemp = ActiveDocument.MailMerge
If mmTemp.State = wdMainAndSourceAndHeader Or _
mmTemp.State = wdMainAndHeader Then
mmTemp.EditHeaderSource
End If
MailMerge.OpenHeaderSource
Attaches a mail merge header source to the specified document.
expression.OpenHeaderSource(Name, Format, ConfirmConversions, ReadOnly, AddToRecentFiles, PasswordDocument, PasswordTemplate, Revert, WritePasswordDocument, WritePasswordTemplate, OpenExclusive)
expression Required. An expression that returns a MailMerge object.
Name Required String. The file name of the header source.
Format Optional Variant. The file converter used to open the document. Can be one of the following WdOpenFormat constants. To specify an external file format, use the OpenFormat property with a FileConverter object to determine the value to use with this argument.
WdOpenFormat can be one of these WdOpenFormat constants.
ConfirmConversions - Optional Variant. True to display the Convert File dialog box if the file isn't in Microsoft Word format.
ReadOnly - Optional Variant. True to open the header source on a read-only basis.
AddToRecentFiles - Optional Variant. True to add the file name to the list of recently used files at the bottom of the File menu.
PasswordDocument - Optional Variant. The password required to open the header source document. (See Remarks below.)
PasswordTemplate - Optional Variant. The password required to open the header source template. (See Remarks below.)
Revert - Optional Variant. Controls what happens if Name is the file name of an open document. True to discard any unsaved changes to the open document and reopen the file; False to activate the open document.
WritePasswordDocument - Optional Variant. The password required to save changes to the document data source. (See Remarks below.)
WritePasswordTemplate - Optional Variant. The password required to save changes to the template data source. (See Remarks below.)
OpenExclusive - Optional Variant. True to open exclusively.
Remarks
When a header source is attached, the first record in the header source is used in place of the header record in the data source.
Security Avoid using hard-coded passwords in your applications. If a password is required in a procedure, request the password from the user, store it in a variable, and then use the variable in your code. For recommended best practices on how to do this, see Security Notes for Microsoft Office Solution Developers.
This example sets the active document as a main document for form letters, and then it attaches the header source named "Header.doc" and the data document named "Names.doc."
With ActiveDocument.MailMerge
.MainDocumentType = wdFormLetters
.OpenHeaderSource Name:="C:\Documents\Header.doc", _
Revert:=False, AddToRecentFiles:=False
.OpenDataSource Name:="C:\Documents\Names.doc"
End With
MailMergeFields Collection Object
A collection of MailMergeField objects that represent the mail merge related fields in a document.
Use the Fields property to return the MailMergeFields collection.
The following example adds an ASK field after the last mail merge field in the active document.
ActiveDocument.MailMerge.Fields.Count
Use Fields(index), where index is the index number, to return a single MailMergeField object.
The following example displays the field code of the first mail merge field in the active document.
MsgBox ActiveDocument.MailMerge.Fields(1).Code
MailMergeField Object
Represents a single mail merge field in a document.
The MailMergeDataField object is a member of the MailMergeDataFields collection.
The MailMergeDataFields collection includes all the mail merge related fields in a document.
Inserting a MergeField
Use the Add method to add a merge field to the MailMergeFields collection.
The following example replaces the selection with a MiddleInitial merge field.
ActiveDocument.MailMerge.Fields.Add Range:=Selection.Range, _
Name:="MiddleInitial"
Range - The range where you want the field to appear. This field replaces the range, if the range isn't collapsed.
Name - The name of the field.
Using the Fields Collection
ActiveDocument.Fields.Add Range:=Selection.Range,
Type:=wdFieldMergeField, _
Text:="""Surname"""
PreserveFormatting:=True
MailMerge.Fields.AddAsk
The MailMergeFields collection has additional methods, such as AddAsk and AddFillIn, for adding fields related to a mail merge operation.
ActiveDocument.MailMerge.Fields.AddAsk Range:=Selection.Range, _
Name:="Name",
Prompt:="Type your name", _
AskOnce:=True
MailMerge.ShowWizard
Displays the Mail Merge Wizard in a document.
expression.ShowWizard(InitialState, _
ShowDocumentStep, _
ShowTemplateStep, _
ShowDataStep, _
ShowWriteStep, _
ShowPreviewStep, _
ShowMergeStep)
expression Required. An expression that returns a MailMerge object.
InitialState - Required Variant. The number of the Mail Merge Wizard step to display.
ShowDocumentStep - Optional Variant. True keeps the "Select document type" step in the sequence of mail merge steps. False removes step one.
ShowTemplateStep - Optional Variant. True keeps the "Select starting document" step in the sequence of mail merge steps. False removes step two.
ShowDataStep - Optional Variant. True keeps the "Select recipients" step in the sequence of mail merge steps. False removes step three.
ShowWriteStep - Optional Variant. True keeps the "Write your letter" step in the sequence of mail merge steps. False removes step four.
ShowPreviewStep - Optional Variant. True keeps the "Preview your letters" step in the sequence of mail merge steps. False removes step five.
ShowMergeStep - Optional Variant. True keeps the "Complete the merge" step in the sequence of mail merge steps. False removes step six.
This example checks if the Mail Merge Wizard is already displayed and, if it is, moves to the Mail Merge Wizard's sixth step and removes the fifth step from the Wizard.
Sub ShowMergeWizard()
With ActiveDocument.MailMerge
If .WizardState > 0 Then
.ShowWizard InitialState:=6, ShowPreviewStep:=False
End If
End With
End Sub
MailMerge.WizardState
Returns or sets a Long indicating the current Mail Merge Wizard step for a document. The WizardState method returns a number that equates to the current Mail Merge Wizard step; a zero (0) means the Mail Merge Wizard is closed. Read/write.
This example checks if the Mail Merge Wizard is already displayed in the active document and if it is, moves to the Mail Merge Wizard's sixth step and removes the fifth step from the Wizard.
Sub ShowMergeWizard()
With ActiveDocument.MailMerge
If .WizardState > 0 Then
.ShowWizard InitialState:=6, ShowPreviewStep:=False
End If
End With
End Sub
© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrev