调用VBA用户窗体中控件的事件过程(使用类模块)

VBA UserForm中组合框的Exit事件 声明格式如下:

Private Sub ComboBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)

如果要在其他地方调用该事件过程,大家首先想到的是Call ComboBox1_Exit(Cancel:=True)

然而这样会弹出类型不匹配的对话框。

第一步:向VBA工程插入一个类模块,命名为ClsReturn,并且书写如下代码:

Implements MSForms.ReturnBoolean
Private V As Boolean
Private Property Get ReturnBoolean_Value() As Boolean
    ReturnBoolean_Value = V
End Property
Private Property Let ReturnBoolean_Value(ByVal RHS As Boolean)
    V = RHS
End Property
Public Property Get Value() As Boolean
    Value = V
End Property
Public Property Let Value(ByVal RHS As Boolean)
    V = RHS
End Property

第二步:向用户窗体放入一个ComboBox控件、两个CommandButton控件。

录入如下代码:

Private Instance As ClsReturn

Private Sub ComboBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Cancel Then
        Debug.Print "点击了第1个按钮"
    Else
        Debug.Print "点击了第2个按钮"
    End If
End Sub
    
Private Sub CommandButton1_Click()
    Instance.Value = True
    Call ComboBox1_Exit(Cancel:=Instance)
End Sub

Private Sub CommandButton2_Click()
    Instance.Value = False
    Call ComboBox1_Exit(Cancel:=Instance)
End Sub

Private Sub UserForm_Initialize()
    Set Instance = New ClsReturn
End Sub

启动窗体,不要碰那个组合框,而是点击两个按钮

你会看到窗体标题变成了:你点击了第两个按钮。

以上做法,还可以应用于其他类型的控件,例如文本框的KeyPress事件等。

原理不解释

大家自己悟

原文地址:https://www.cnblogs.com/ryueifu-VBA/p/12925676.html