VBA Excel-如何使用 MS Excel 中的取消按钮关闭?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14398652/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:45:55  来源:igfitidea点击:

VBA Excel-How to work with cancel button in the MS Excel close?

exceleventsvbamessagebox

提问by SaiKiran Mandhala

I am running a macro while in Private Sub Workbook_BeforeClose(Cancel As Boolean)but whenever user clicks on Cancelbutton macro should not run.

我正在运行一个宏,Private Sub Workbook_BeforeClose(Cancel As Boolean)但每当用户点击取消按钮时,宏都不应该运行。



I kept following lines of code

我一直在遵循代码行

Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cancel = True Then
    MsgBox "You clicked on Cancel"
ElseIf Cancel = False Then
    Call SDA
End If

End Sub
But whenever i press Cancelbutton it is not showing me any MessageBox.Any help would be appreciated greatly.enter image description here

End Sub
但是,每当我按下取消按钮时,它都不会向我显示任何 MessageBox。任何帮助将不胜感激。在此处输入图片说明

回答by bonCodigo

Try this please:

请试试这个:

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim Msg As String
Dim ireply As Integer
    If Not Me.Saved Then
        Msg = "Do you want to Save this book? "
        ireply = MsgBox(Msg, vbQuestion + vbYesNoCancel)
        Select Case ireply
            Case vbYes
                Me.Save
                Call SDA 
            Case vbNo
                Me.Saved = True
            Case vbCancel
                Cancel = True
                MsgBox "Cancelling...workbook close event!"
                Exit Sub
          End Select
    End If        
End Sub
  • Output dialogs:
  • 输出对话框:

enter image description here

在此处输入图片说明

The usual structure of a messagebox cancel event wrap is as follows:

消息框取消事件包装的通常结构如下:

'--Display MessageBox
    Dim intMsg as integer
    intMsg = MsgBox(strPrompt, vbYesNo, strTitle) 
    '--Check pressed button
    If iRet = vbNo Then
        MsgBox "NO!"
    Else
        MsgBox "Yes!"
    End If