简体   繁体   中英

Checking if file exists before exporting

I have come across a macro from a user on this site but noticed it doesn't rename the file if already exists. Can someone please help;

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 & ".docx"
        Else
           strDocName = ActiveDocument.MailMerge.DataSource.DataFields(docNameField).Value
       End If

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

        ' Save generated document and close it after saving
        ActiveDocument.ExportAsFixedFormat _
        OutputFileName:=savePath & strDocName & ".pdf", _
        ExportFormat:=wdExportFormatPDF
        ActiveDocument.Close False

        ActiveDocument.MailMerge.DataSource.ActiveRecord = wdNextRecord
    Next rec

I have seen a few guidlines on how to do this using manual pointers to save file location but within this sameple "savepath" is already defined based on the directory the file is in.

I am thinking something like the following;

Do While .FileExists(strPath)

    i = i + 1

    OutputFileName:=savePath & strDocName & i, _
        ExportFormat:=wdExportFormatPDF
        ActiveDocument.Close False
Loop

I am unsure how to proceed / whether this is correct and would appreciate any advice.

I am providing a FileExists function:

Public Function FileExists(sFileName As String) As Boolean
  Dim obj_fso As Object

  Set obj_fso = CreateObject("Scripting.FileSystemObject")
  FileExists = obj_fso.fileExists(sFileName)

  Set obj_fso = Nothing
End Function

A simple function to check if a file exists. While Scripting.FileSystemObject works fine, it's extremely slow. Dir() is much quicker.

Public Function FileExists(ByVal Filename As String) As Boolean
     FileExists = Len(Dir(Filename, vbDirectory)) > 0
End Function


If FileExists("Some path") then ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM