导出前检查文件是否存在

时间:2018-02-08 14:23:27

标签: vba excel-vba excel

我在本网站上遇到过来自用户的宏,但发现如果该文件已经存在,则不会重命名该文件。有人可以帮忙;

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

我已经看到了一些关于如何使用手动指针来保存文件位置的指导,但是在这个内容和#34; savepath"已根据文件所在的目录定义。

我正在考虑以下内容;

Do While .FileExists(strPath)

    i = i + 1

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

我不确定如何处理/这是否正确,并希望得到任何建议。

2 个答案:

答案 0 :(得分:0)

我正在提供FileExists功能:

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

答案 1 :(得分:0)

检查文件是否存在的简单函数。虽然Scripting.FileSystemObject工作正常,但速度极慢。 Dir()要快得多。

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


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