[英]Saveas issue Overwrite existing file ( Excel VBA)
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. 但是,当我进入“ SaveAs
部分时,当选择“ No
进行保存时会出现以下错误。 Excel message: A file named " ......... " already exists in this location. Excel消息: 此位置已存在名为“.........”的文件。 Do you want to replace it ? 您要更换它吗? I click 'No' or cancel
and get the run time error 1004 .... Method SaveAs
of object _Workbook
failed. 我单击“否”或cancel
并得到运行时错误1004...。对象_Workbook
方法SaveAs
失败。
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
,因为我希望用户知道有一个已经命名相同的文件。
No
or Cancel
and not get the run-time error.? 我还需要显示什么其他选项来显示文件已经存在,然后选择“ No
或“ Cancel
而不会出现运行时错误。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.