2

在 Excel-VBA 中,我使用以下代码保存文件:

fullFileName = Application.GetSaveAsFilename(...)
ActiveWorkbook.SaveAs fullFileName

这工作正常,直到选择的名称已经存在。然后消息框提示:“是否应该替换文件?”。我要回答No,然后返回上一个消息框并选择另一个名称。

相反,单击No会中断宏并产生错误。

我怎么能解决这个问题?

(网络上充满了展示如何使用Application.DisplayAlerts=False并保存绕过此消息框的示例。这不是我想要的!)

4

1 回答 1

3

我一般用这个...

Sub Sample()
    Dim fullFileName

    fullFileName = Application.GetSaveAsFilename( _
                   fileFilter:="Text Files (*.txt), *.txt")
    If fullFileName <> False Then
        If fileExists(fullFileName) = False Then
            ActiveWorkbook.SaveAs fullFileName
        Else
            MsgBox "File Exists. File Save Aborted"
        End If
    End If
End Sub

Public Function fileExists(strFullPath As Variant) As Boolean
    On Error GoTo Whoa
    If Not Dir(strFullPath, vbDirectory) = vbNullString Then fileExists = True
Whoa:
    On Error GoTo 0
End Function

跟进

你的意思是这样吗?

Sub Sample()
    Dim fullFileName
    Dim conti As Boolean

    conti = True

    Do While conti = True
        fullFileName = Application.GetSaveAsFilename( _
                       fileFilter:="Text Files (*.txt), *.txt")
        If fullFileName <> False Then
            If fileExists(fullFileName) = False Then
                ActiveWorkbook.SaveAs fullFileName
                conti = False
            Else
                MsgBox "File Exists. Returning you back to the dialog box"
            End If
        Else
            conti = False
        End If
    Loop
End Sub

Public Function fileExists(strFullPath As Variant) As Boolean
    On Error GoTo Whoa
    If Not Dir(strFullPath, vbDirectory) = vbNullString Then fileExists = True
Whoa:
    On Error GoTo 0
End Function
于 2012-07-31T10:41:50.040 回答