PDA

View Full Version : Check If File Exists Mailmerge MAcro



azhar0702
02-12-2018, 04:31 AM
Hi

I am trying to implement a method of cecking the proposed save name for each mailmerge record. If it already exists i would like the document to be renamed to example-1. Can someone please assist?

Below is a link to the full code with my attempt highlighted in yellow

https://swissmacuser.ch/microsoft-word-mail-merge-into-single-documents/#.WoF6UKhl-71


ActiveDocument.MailMerge.DataSource.ActiveRecord = wdLastRecord
lastRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord

' Ask for user confirmation to start creating the documents
If MsgBox(lastRecord & " documents will be created based on your Mail Merge template.", vbOKCancel) = vbOK Then

' Ask for the name of the Merge Field name to use for the document names
docNameField = "PID"

' Create document for each Mail Merge record (loop)
For rec = ActiveDocument.MailMerge.DataSource.FirstRecord To lastRecord

ActiveDocument.MailMerge.DataSource.ActiveRecord = rec

' Set document name for current record


If Trim(docNameField) = "" Then
strDocName = "document" & rec
Else
strDocName = ActiveDocument.MailMerge.DataSource.DataFields(docNameField).Value
End If

' Execute Mail Merge action
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.Execute
End With

fName = savePath & strDocName
If Len(Dir(fName, vbNormal)) = 0 Then
strDocName = strDocName
Else

Do Until Len(Dir(fName, vbNormal)) = 0
i = i + 1
fName = fName & i
Loop

End If

' Save generated document and close it after saving
ActiveDocument.ExportAsFixedFormat _
OutputFileName:=fName, _
ExportFormat:=wdExportFormatPDF
ActiveDocument.Close False

ActiveDocument.MailMerge.DataSource.ActiveRecord = wdNextRecord
Next rec

gmaxey
02-12-2018, 06:02 AM
You could pass the file path and name to a function and evaluate the returned result:


Public Function fcnFileOrFolderExist(PathName As String) As Boolean
'Macro Purpose: Function returns TRUE if the specified file or folder exists, false if not.
'PathName: Supports Windows mapped drives
'File usage: Provide full file path and extension
'Folder usage: Provide full folder path
Dim lngTemp As Long
'Ignore errors to allow for error evaluation
On Error Resume Next
lngTemp = GetAttr(PathName)
'Check if error exists and set response appropriately
Select Case Err.Number
Case Is = 0
fcnFileOrFolderExist = True
Case Else
fcnFileOrFolderExist = False
End Select
'Resume error checking
On Error GoTo 0
lbl_Exit:
Exit Function
End Function