在 Excel-VBA 中,我使用以下代码保存文件:
fullFileName = Application.GetSaveAsFilename(...)
ActiveWorkbook.SaveAs fullFileName
在所选名称已经存在之前,此操作正常。然后消息框提示:“是否应该替换该文件?”。我想回答否
,然后返回到上一个消息框并选择另一个名称。
相反,单击否
会中断宏并产生错误。
我该如何解决这个问题?
(网络上有很多示例展示如何使用 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
关于vba - 单击 "No"替换文件时如何返回“保存”消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11738229/