vba - 单击 "No"替换文件时如何返回“保存”消息框

标签 vba excel messagebox savefiledialog

在 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/

相关文章:

Excel 求和与相对位置

c# - 在没有用户输入的情况下以编程方式拆卸 MessageBox

.net - 为什么 System.Windows.MessageBoxImage 有相同值的枚举子项?

arrays - 使用范围填充数组)单元格

vba - VBA : Search, save and replace by rows according to conditions

vba - 用户定义的函数不会在 excel 上更新

mySQL + vba,检查表中是否已存在某个项目

python - 使用另一个文件中的函数通过 xlsx 写入 Excel

excel - 删除所有没有#3作为主键开头的行

c++ - Messagebox 检测 YesNoCancel 按钮