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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15967659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:23:05  来源:igfitidea点击:

Saveas issue Overwrite existing file ( Excel VBA)

vbaexcel-vbaexcel

提问by Vikash

I have the following macro that is correct except for the SaveAsgives me an error if I click Noor Cancel,if I click yesis working fine.

我有以下正确的宏,除了SaveAs如果我点击NoCancel如果我点击yes工作正常会给我一个错误。

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

Application.DisplayAlert =True

But when I come to SaveAspart I get the following error when I select Noto the save. Excel message: A file named " ......... " already exists in this location. Do you want to replace it? I click 'No' or canceland get the run time error 1004 .... Method SaveAsof object _Workbookfailed.

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

I don't want to use the Application.DisplayAlerts = False, because I want the user to be aware that there is a file already named the same.

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

  1. Why do I get this error? Why can't I select 'No'
  2. What other option do I have to display that the file is already there and select Noor Canceland not get the run-time error.?
  1. 为什么我会收到这个错误?为什么我不能选择“否”
  2. 我还有什么其他选项可以显示文件已经存在并选择NoCancel不出现运行时错误。?

回答by Siddharth Rout

Try this method.

试试这个方法。

I have commented the code so you shouldn't have any problem understanding it. Still if you do then simply ask :)

我已经注释了代码,所以你理解它应该没有任何问题。尽管如此,如果你这样做,那么简单地问:)

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