选择"否"时出现VBA错误或"取消"当在SaveAs期间要求替换文件时

时间:2017-01-30 19:45:18

标签: excel vba excel-vba

我有用于将工作簿保存在具有特定名称的特定文件夹中的代码。当文件已存在时,问题就出现了。我有" ConflictResolution"设置为询问用户,但我得到"运行时错误1004:方法保存对象_Workbook失败"当用户在对话框中选择NoCancel

我不确定如何或者是否可以退出NoCancel,或者我是否应该在此部分添加自定义错误处理?

  NewFileType = "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm," & _
               "All files (*.*), *.*"

    NewFile = Application.GetSaveAsFilename( _
        InitialFileName:=SaveArea & newfilename, _
        fileFilter:=NewFileType)

    If NewFile <> "" And NewFile <> "False" Then
        ActiveWorkbook.SaveAs FileName:=NewFile, _
            FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
            CreateBackup:=False, _
            ConflictResolution:=xlUserResolution
    End If

1 个答案:

答案 0 :(得分:3)

您应该处理SaveAs方法引发的错误。例如。

 If NewFile <> "" And NewFile <> "False" Then
    On Error Resume Next
    ActiveWorkbook.SaveAs Filename:=NewFile, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
        CreateBackup:=False, _
        ConflictResolution:=xlUserResolution
    If Err.Number <> 0 Then
        MsgBox Err.Description
    End If
    On Error GoTo 0
 End If

或者,在调用SaveAs之前检查文件是否存在