excel工作簿关闭时是否可以显示警告两次?

时间:2017-01-15 10:05:00

标签: vba excel-vba excel

我正在构建一个代码,该代码在工作簿关闭时发出警告。默认情况下,excel仅警告一次(如果未保存当前更改,则也是如此)。我想要警告两次。第一次应该问你确定吗?当这个人点击是的时候,系统应该问你确定。

到目前为止,我的代码如下,但它无法正常工作。使用以下代码,警告仅显示一次。请有人帮忙吗?

Private Sub Workbook_BeforeClose(Cancel As Boolean)
 Dim mbResult As Integer
Dim wkb As Workbook
Set wkb = ActiveWorkbook

mbResult = MsgBox("Are you sure you want to exit this program?", _
 vbYesNo)

    Select Case mbResult
    Case vbYesNo
        MsgBox "You are about to exit this program, are you sure?"
        Case vbYes
Cancel = True

        Case vbNo
          ' Do nothing and allow the macro to run

    Exit Sub

End Select

End Sub

2 个答案:

答案 0 :(得分:0)

您可以使用Workbook_BeforeClose事件来提示用户检查他们是否真的想要做某事。

以下这两个代码都要求用户两次确认是否要关闭工作簿。第一个使用Workbook_BeforeClose事件,因此您需要在代码中执行一些操作以保存更改等。

Private Sub Workbook_BeforeClose(Cancel As Boolean)
  If MsgBox("Are you sure you want to close the workbook?", vbYesNo, "User Input") = vbYes Then
        If MsgBox("Are you relly sure you want to close the workbook?", vbYesNo, "User Input") = vbYes Then
           Call MsgBox("No turning back now", vbOKOnly, "User Anwser")
        End If
    Else
        Call MsgBox("That was close", vbOKOnly, "User Anwser")
    End If
End Sub

第二组代码进入普通模块,当您希望用户关闭工作簿时,可以从宏中调用它。我已经放入了一个工作簿保存,以便不会丢失更改。

Sub Close()
  If MsgBox("Are you sure you want to close the workbook?", vbYesNo, "User Input") = vbYes Then
        If MsgBox("Are you relly sure you want to close the workbook?", vbYesNo, "User Input") = vbYes Then
           Call MsgBox("No turning back now", vbOKOnly, "User Anwser")
           ActiveWorkbook.Close True
        End If
    Else
        Call MsgBox("That was close", vbOKOnly, "User Anwser")
    End If
End Sub

它看起来如何运行,

enter image description here

答案 1 :(得分:0)

你可以像这样直接处理MsgBox的返回值:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Select Case MsgBox("Are you sure you want to exit this file?", vbYesNo)
        Case vbYes
            Cancel = MsgBox("You are about to exit this program, are you sure?", vbYesNo) = vbNo
        Case vbNo
            Cancel = True
    End Select
End Sub

或,等同于:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Cancel = MsgBox("Are you sure you want to exit this file?", vbYesNo) = vbNo
    If Not Cancel Then Cancel = MsgBox("You are about to exit this program, are you sure?", vbYesNo) = vbNo
End Sub