簡體   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