是的,这是可能的。但是,您需要一种面向对象的方法。 你首先需要定义一个引发你想要钩入的事件的类。其次,您需要一个实际处理事件的类,因为您不能在常规模块中使用事件处理程序。 第三,在你的常规模块中,你可以使用这些类。
下面是一个简单的例子: 创建一个名为“ClassWithEvent”的类模块。放置以下代码:
Public Event VariableChange(value As Integer)
Private p_int As Integer
Public Property Get value() As Integer
value = p_int
End Property
Public Property Let value(value As Integer)
If p_int <> value Then RaiseEvent VariableChange(value) 'Only raise on actual change.
p_int = value
End Property
接下来,创建一个可处理此类所引发事件的类。 将此类模块命名为“ClassHandlesEvent”。下面的代码放置在它:
Private WithEvents SomeVar As ClassWithEvent
Private Sub SomeVar_VariableChange(value As Integer) 'This is the event handler.
Select Case value
Case 1:
MsgBox "here, 1!"
Case 2:
MsgBox "here, 2!"
Case Default:
'Do Nothing
End Select
End Sub
Public Property Get EventVariable() As ClassWithEvent
Set EventVariable = SomeVar
End Property
Public Property Let EventVariable(value As ClassWithEvent)
Set SomeVar = value
End Property
接下来,在常规模块,实例化ClassWithEvent并通过这一个作为一个属性到处理它们的类。
Sub test()
Dim var As ClassHandlesEvent
Dim tst As ClassWithEvent
Set var = New ClassHandlesEvent
Set tst = New ClassWithEvent
var.EventVariable = tst
tst.value = 2 'A messagebox saying "Here, 2!" will pop-up
End Sub
我可能会建议的增强功能只会在变量发生变化时才引发事件。目前,如果您再次将值设置为2,您将获得一个事件。 –
@BrianMStafford你是对的。修改代码以检查值是否不相等。 –
我的朋友,我真诚感谢您的详细解答,并为您抽出时间向我展示这一点。我需要一点点关注一步一步发生的事情。我可以告诉你的答案完美无瑕。 – Quint