Here is a macro that can be used to do a mail merge with formfields if the
datasource is a table in an Access Database. The mail merge main document
must be set up with the data source attached and the merge fields inserted
into the document. It can be used with a document that contains any type of
formfield and creates a separate document for each record in the data source
with a filename of the format MwithFF# in a folder c:\Test (that must be
created on your system). You can change the MwithFF to something else if
you want and also the folder into which the documents are saved by modifying
the
..SaveAs "C:\Test\MwithFF" & j
line of code.
Sub MailMergewithFormFields()
Dim dSource As String
Dim qryStr As String
Dim mfCode As Range
Dim i As Long, j As Long
Dim db As DAO.Database
Dim rs As DAO.Recordset
With ActiveDocument
'Get the details of the datasource
With .MailMerge.DataSource
dSource = .Name
qryStr = .QueryString
End With
'Convert the MERGEFIELDS to DOCVARIABLE fields
For i = 1 To .Fields.Count
If .Fields(i).Type = wdFieldMergeField Then
Set mfCode = .Fields(i).code
mfCode = Replace(mfCode, "MERGEFIELD", "DOCVARIABLE")
End If
Next i
'Convert the Mail Merge Main document to a normal Word document
.MailMerge.MainDocumentType = wdNotAMergeDocument
.Protect wdAllowOnlyFormFields, NoReset
End With
' Open the database
Set db = OpenDatabase(dSource)
' Retrieve the recordset
Set rs = db.OpenRecordset(qryStr)
With rs
' Move to the first record
.MoveFirst
j = 1
Do While Not .EOF
'Create variables in the document with the names and values of the
fields in each record
For i = 0 To .Fields.Count - 1
If .Fields(i).Value <> "" Then
ActiveDocument.Variables(.Fields(i).Name).Value =
..Fields(i).Value
End If
Next i
With ActiveDocument
.Fields.Update
.SaveAs "C:\Test\MwithFF" & j
End With
.MoveNext
j = j + 1
Loop
End With
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Sub
If you data source is not in that format, the following macro can be used to
execute the merge to a new document in which the formfields that were in the
mailmerge main document, will be reinstated into each of the "letters"
contained in that new document:
Sub MergewithFormFields()
Dim i As Long
With ActiveDocument
For i = .FormFields.Count To 1 Step -1
If .FormFields(i).Type = wdFieldFormTextInput Then
.FormFields(i).Range.Text = "FF" & i
End If
Next i
With .MailMerge
.Destination = wdSendToNewDocument
.Execute
End With
End With
Selection.HomeKey wdStory
With Selection.Find
Do While .Execute(FindText:="FF[0-9]{1,}", Forward:=True, _
MatchWildcards:=True, Wrap:=wdFindStop, MatchCase:=True) = True
ActiveDocument.FormFields.Add Selection.Range, wdFieldFormTextInput
Loop
End With
End Sub
--
Hope this helps.
Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.
Doug Robbins - Word MVP, originally posted via msnews.microsoft.com