處理 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