Apologies if this is posted in the wrong section - please advise
I have a word script to where I am pulling data from excel spreadsheet 'ADO' and creating a basic mail merge (saving each letter in a folder) but not sending them... Lets say on Sheet ADO I have 10 rows of data the script below will stop on the 11th row and because its empty it will open a separate blank template? I want it to stop on the row where the data ends and not open the final word document.
Also, is there any way to close the word document once the macro has been run?
Cheers in advance
I have a word script to where I am pulling data from excel spreadsheet 'ADO' and creating a basic mail merge (saving each letter in a folder) but not sending them... Lets say on Sheet ADO I have 10 rows of data the script below will stop on the 11th row and because its empty it will open a separate blank template? I want it to stop on the row where the data ends and not open the final word document.
Also, is there any way to close the word document once the macro has been run?
Cheers in advance
VBA Code:
Option Explicit
Const FOLDER_SAVED As String = "PATH_HERE"
Const SOURCE_FILE_PATH As String = "FILE_HERE"
Sub TestRun()
Dim MainDoc As Document, TargetDoc As Document
Dim dbPath As String
Dim recordNumber As Long, totalRecord As Long
Set MainDoc = ActiveDocument
With MainDoc.MailMerge
'// if you want to specify your data, insert a WHERE clause in the SQL statement
.OpenDataSource Name:=SOURCE_FILE_PATH
totalRecord = .DataSource.RecordCount
For recordNumber = 1 To totalRecord
With .DataSource
.ActiveRecord = recordNumber
.FirstRecord = recordNumber
.LastRecord = recordNumber
End With
.Destination = wdSendToNewDocument
.Execute False
Set TargetDoc = ActiveDocument
TargetDoc.SaveAs2 FOLDER_SAVED & .DataSource.DataFields("File_Name").Value & ".pdf", wdFormatDocumentDefault
TargetDoc.ExportAsFixedFormat FOLDER_SAVED & .DataSource.DataFields("File_Name").Value & ".pdf", exportformat:=wdExportFormatPDF
TargetDoc.Close True
Set TargetDoc = Nothing
Next recordNumber
End With
Set MainDoc = Nothing
End Sub