繁体   English   中英

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

[英]Saveas issue Overwrite existing file ( Excel VBA)

我有以下正确的宏,除了SaveAs会给我一个错误,如果我单击“ No或“ Cancel ,如果我单击“ yes则工作正常。

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

Application.DisplayAlert =True

但是,当我进入“ SaveAs部分时,当选择“ No进行保存时会出现以下错误。 Excel消息: 此位置已存在名为“.........”的文件。 您要更换它吗? 我单击“否”或cancel并得到运行时错误1004...。对象_Workbook方法SaveAs失败。

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

  1. 为什么我会收到此错误? 为什么我不能选择“否”
  2. 我还需要显示什么其他选项来显示文件已经存在,然后选择“ No或“ Cancel而不会出现运行时错误。

试试这个方法。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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