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

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

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

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

而是,单击No中断macros并产生一个错误。

我怎么能解决这个问题?

(网上有很多例子,展示了如何使用Application.DisplayAlerts=False来绕过这个消息框,然后保存,这不是我想要的!)

这通常是我使用的…

 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