且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-08 14:13:24

尝试此方法.

我已注释了该代码,因此您在理解它时应该没有任何问题.如果您仍然这样做,则只需问:)

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