Excel VBA:确认按下命令按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16839149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA: Confirmation on Pressing CommandButton
提问by jcv
Upon pressing my CommandButton, I would like to have a pop-up that asks "These changes cannot be undone. It is advised to save a copy before proceeding. Do you wish to proceed?"
按下我的命令按钮后,我想要一个弹出窗口,询问“这些更改无法撤消。建议在继续之前保存副本。您想继续吗?”
And I want to have three options:
我想有三个选择:
- Yes - pop-up window is closed and CommandButton Macro is executed
- No - This closes the pop-up window and changes nothing
- Save - closes pop-up window and opens "Save As" (macro is not executed)
- 是 - 弹出窗口关闭并执行命令按钮宏
- 否 - 这将关闭弹出窗口并且不做任何更改
- 保存 - 关闭弹出窗口并打开“另存为”(不执行宏)
I don't really know where to start with this. Could you please give me a hand?
我真的不知道从哪里开始。你能帮我一把吗?
Thank you very much indeed.
真的非常感谢。
回答by David Zemens
You can use a message box, but that is somewhat limited. You can rephrase the question slightly to use the vbYesNoCancel
buttons, since Save As
is not an optional button on Message Box.
您可以使用消息框,但这有些限制。您可以稍微改写问题以使用vbYesNoCancel
按钮,因为Save As
它不是 Message Box 上的可选按钮。
Then you can work with the result of the message box button-click:
然后您可以使用消息框按钮单击的结果:
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
回答by GTG
I suggest you put code at the top of your macro to ask this question and respond to the answer.
我建议你将代码放在宏的顶部来提出这个问题并回答答案。
This would look something like:
这看起来像:
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.
Note that this will not give the user the Save option. You can't do that with a standard MsgBox. If you want to do that, you will need to create your own userform, show that instead of the MsgBox and respond to what button in the Userform the user pushed. That is a lot more work for you than just using a MsgBox, but if you want your UI to be fancy, it may be worth it.
请注意,这不会为用户提供“保存”选项。你不能用标准的 MsgBox 做到这一点。如果你想这样做,你需要创建你自己的用户表单,显示它而不是 MsgBox 并响应用户按下的用户表单中的哪个按钮。这对您来说比仅使用 MsgBox 需要做的工作要多得多,但是如果您希望您的 UI 漂亮一些,那么这可能是值得的。