Excel VBA:按CommandButton确认

jcv*_*jcv 6 excel vba excel-vba

按下我的CommandButton后,我想要一个弹出窗口,询问"这些更改无法撤消.建议在继续之前保存副本.是否要继续?"

我想有三个选择:

  1. 是 - 关闭弹出窗口并执行CommandButton宏
  2. 否 - 这会关闭弹出窗口并且不会更改任何内容
  3. 保存 - 关闭弹出窗口并打开"另存为"(未执行宏)

我真的不知道从哪里开始.你能帮我个忙吗?

非常感谢你.

Dav*_*ens 19

您可以使用消息框,但这有点受限.您可以稍微改写问题以使用vbYesNoCancel按钮,因为Save As它不是消息框上的可选按钮.

然后你可以使用消息框的结果按钮 - 单击:

Dim mbResult as Integer
mbResult = MsgBox("These changes cannot be undone. Would you like to save a copy before proceeding?", _
 vbYesNoCancel)

Select Case mbResult
    Case vbYes
        'Modify as needed, this is a simple example with no error handling:
        With ActiveWorkbook
            If Not .Saved Then .SaveAs Application.GetSaveAsFilename()
        End With
    Case vbNo
        ' Do nothing and allow the macro to run

    Case vbCancel
        ' Do NOT allow the macro to run
        Exit Sub

End Select
Run Code Online (Sandbox Code Playgroud)

  • +1同时添加一个If Not ActiveWorkbook.Saved然后你甚至不知道工作簿是否已经保存. (3认同)

GTG*_*GTG 7

我建议你把代码放在宏的顶部来问这个问题并回答答案.

这看起来像是这样的:

Sub YourMacro()

  if MsgBox("These changes cannot be undone. It is advised to save a copy before proceeding. Do you wish to proceed?", vbYesNo + vbQuestion) = vbNo then
    exit sub
  end if

  ... the rest of your macro.
Run Code Online (Sandbox Code Playgroud)

请注意,这不会为用户提供"保存"选项.你不能用标准的MsgBox做到这一点.如果你想这样做,你需要创建自己的用户表单,显示而不是MsgBox并响应用户推送的Userform中的哪个按钮.除了使用MsgBox之外,这对你来说还有很多工作要做,但如果你想要你的UI很花哨,那么它可能是值得的.