单击“否”替换文件时如何返回保存消息框

时间:2012-07-31 10:37:40

标签: excel vba excel-vba messagebox savefiledialog

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

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

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

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

我怎么解决这个问题?

(网上有很多示例显示如何使用Application.DisplayAlerts=False绕过此消息框并保存。这不是我想要的!)

1 个答案:

答案 0 :(得分: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