是的,這是可能的。但是,您需要一種面向對象的方法。 你首先需要定義一個引發你想要鉤入的事件的類。其次,您需要一個實際處理事件的類,因爲您不能在常規模塊中使用事件處理程序。 第三,在你的常規模塊中,你可以使用這些類。
下面是一個簡單的例子: 創建一個名爲「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