Saveas问题覆盖现有文件(Excel VBA)

Vik*_*ash 2 excel vba excel-vba

我有以下宏是正确的,除非SaveAs我点击No或给我一个错误Cancel,如果我点击yes工作正常.

ActiveWorkbook.SaveAs Filename:=FileName, FileFormat:=xlWorkbook, ConflictResolution:=xlLocalSessionChanges

Application.DisplayAlert =True
Run Code Online (Sandbox Code Playgroud)

但是当我SaveAs选择No保存时,我遇到了以下错误.Excel消息:此位置已存在名为"........."的文件.你想替换它吗?我单击"否"或cancel得到运行时错误1004 .... SaveAs对象方法_Workbook失败.

我不想使用Application.DisplayAlerts = False,因为我希望用户知道有一个已经命名相同的文件.

  1. 为什么我会收到此错误?为什么我不能选择'不'
  2. 我还有什么其他选项可以显示文件已存在并选择NoCancel不获取运行时错误.

Sid*_*out 7

试试这个方法.

我已对代码进行了评论,因此您不应该对它有任何问题.如果你这样做,那么干脆问:)

Sub Sample()
    Dim fName As Variant

    '~~> Offer user to Save the file at a particular location
    fName = Application.GetSaveAsFilename

    '~~> Check if it is a valid entry
    If fName <> False Then
        '~~> Check before hand if the file exists
        If Not Dir(fName) <> "" Then
            '~~> If not then save it
            ActiveWorkbook.SaveAs Filename:=fName
        Else
            '~~> Trap the error and ignore it
            On Error Resume Next
            If Err.Number = 1004 Then
                On Error GoTo 0
            Else '<~~ If user presses Save
                ActiveWorkbook.SaveAs Filename:=fName, _
                FileFormat:=xlWorkbook, _
                ConflictResolution:=xlLocalSessionChanges
            End If
        End If
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)