I'm having some type of fault with my code, but I'm not sure what. This code was working for me less than a month ago.
What I am trying to do: Have it spit out a mail merge letter for each address in the database.
The result of my code: Depending on how many addresses I check telling it gives me that many exact replicas of the template filled with the FIRST and LAST entries of the database.
Example: I check off 18 addresses in the database and pass that variable to be in my export table. It spits out 18 microsoft word files, each word file has a copy of the template filled in with the first address filled in on page 1 and the last address filled in on page 2.
What am I doing wrong?
Private Sub MailMerge(ClientTemplate As String)
Dim Word As Object
Dim Doc As Object
Dim Sel As Object
Dim nRows As Integer
Set Word = CreateObject("Word.Application")
Set Doc = Word.Documents.Open(ClientTemplate)
Set Sel = Word.Selection
nRows = DCount("*", "tblFinalMailMerge")
With Word
.Visible = True
.Application.Activate
'.Documents.Open (ClientTemplate)
End With
With Doc.MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.OpenDataSource Name:=CurrentDb.Name, SQLStatement:="SELECT * FROM [tblFinalMailMerge]"
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
For x = 1 To nRows
With Doc.MailMerge.DataSource
.ActiveRecord = x
If ActiveRecord > .LastRecord Then Exit For
End With
Word.ActiveDocument.SaveAs _
FileName:="C:\temp\test" & x & ".docx"
Next x