Thread: Mail Merge Code
View Single Post
 
Old 10-03-2020, 04:57 AM
dlafko1 dlafko1 is offline Windows 10 Office 2016
Advanced Beginner
 
Join Date: Apr 2019
Posts: 31
dlafko1 is on a distinguished road
Default Mail Merge Code

I am trying to get this code to work (novice to vba ) this was something shared.

I keep getting an error 5174 couldn't find your file. I know the location and file names are correct any help

Code:
Option Explicit

Const FOLDER_SAVED As String = "C:\Users\david\Desktop\PhotoRelease\"
Const SOURCE_FILE_PATH As String = "C:\Users\david\Desktop\PhotoRelease\ScoutRoster.xls\"

Sub MailMerge_Automation()
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, sqlstatement:="SELECT * FROM [database$]"
            
        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("Name").Value & ".docx", wdFormatDocumentDefault
            TargetDoc.ExportAsFixedFormat FOLDER_SAVED & .DataSource.DataFields("Name").Value & ".pdf", exportformat:=wdExportFormatPDF
            
            TargetDoc.Close False
            
            Set TargetDoc = Nothing
                    
        Next recordNumber

End With

Set MainDoc = Nothing
End Sub
Reply With Quote