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
Saveas issue Overwrite existing file ( Excel VBA)
提问by Vikash
I have the following macro that is correct except for the SaveAs
gives me an error if I click No
or Cancel
,if I click yes
is working fine.
我有以下正确的宏,除了SaveAs
如果我点击No
或Cancel
如果我点击yes
工作正常会给我一个错误。
ActiveWorkbook.SaveAs Filename:=FileName, FileFormat:=xlWorkbook, ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlert =True
But when I come to SaveAs
part I get the following error when I select No
to the save.
Excel message: A file named " ......... " already exists in this location. Do you want to replace it? I click 'No' or cancel
and get the run time error 1004 ....
Method SaveAs
of object _Workbook
failed.
但是当我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
,因为我希望用户知道有一个文件已经命名为相同。
- Why do I get this error? Why can't I select 'No'
- What other option do I have to display that the file is already
there and select
No
orCancel
and not get the run-time error.?
- 为什么我会收到这个错误?为什么我不能选择“否”
- 我还有什么其他选项可以显示文件已经存在并选择
No
或Cancel
不出现运行时错误。?
回答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