[英]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
,因為我希望用戶知道有一個已經命名相同的文件。
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.