处理 QueryClose

只要表单即将关闭,无论是通过用户操作还是以编程方式,都会引发 QueryClose 事件。CloseMode 参数包含 VbQueryClose 枚举值,表示窗体是如何关闭的:

不变 描述
vbFormControlMenu 表单正在关闭以响应用户操作 0
vbFormCode 表格将根据 Unload 声明结束 1
vbAppWindows Windows 会话即将结束 2
vbAppTaskManager Windows 任务管理器正在关闭主机应用程序 3
vbFormMDIForm VBA 不支持 4

为了更好的可读性,最好使用这些常量而不是直接使用它们的值。

可取消的用户窗体

给出一个带 Cancel 按钮的表单

一些样本表格

表单的代码隐藏可能如下所示:

Option Explicit
Private Type TView
    IsCancelled As Boolean
    SomeOtherSetting As Boolean
    'other properties skipped for brievety
End Type
Private this As TView

Public Property Get IsCancelled() As Boolean
    IsCancelled = this.IsCancelled
End Property

Public Property Get SomeOtherSetting() As Boolean
    SomeOtherSetting = this.SomeOtherSetting
End Property

'...more properties...

Private Sub SomeOtherSettingInput_Change()
    this.SomeOtherSetting = CBool(SomeOtherSettingInput.Value)
End Sub

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    this.IsCancelled = True
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        Cancel = True
        this.IsCancelled = True
        Me.Hide
    End If
End Sub

然后调用代码可以显示表单,并知道它是否被取消:

Public Sub DoSomething()
    With New UserForm1
        .Show vbModal
        If .IsCancelled Then Exit Sub
        If .SomeOtherSetting Then
            'setting is enabled
        Else
            'setting is disabled
        End If
    End With
End Sub

Cancel 单击按钮时,或当用户使用控制框关闭表单时,IsCancelled 属性返回 True