Qui*_*int 4 excel vba excel-vba access-vba
是否可以通过更改变量来触发事件?例如。
这将触发事件
Dim t As Integer
Dim Fire As Boolean
Private Sub Test
t = 0
Fire = True
IIf Fire, t=1, t=2
End sub
Run Code Online (Sandbox Code Playgroud)
在事件处理程序中
Select Case t
Case 0
'Do something
Case 1
'Do something
Case 2
'Do something
Case 3
'Do something
...
Run Code Online (Sandbox Code Playgroud)
Google调出了事件处理程序,并使用了类模块,但是我无法解决这个问题。
是的,这是可能的。但是,您将需要一种面向对象的方法。首先,您需要定义一个引发您希望挂接的事件的类。其次,您将需要一个实际处理事件的类,因为您不能在常规模块中使用事件处理程序。第三,在常规模块中,您可以只使用这些类。
这是一个简单的示例:创建一个名为“ 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
Run Code Online (Sandbox Code Playgroud)
接下来,创建可以处理此类引发的事件的类。将此类模块命名为“ 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
Run Code Online (Sandbox Code Playgroud)
接下来,在常规模块中,实例化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
Run Code Online (Sandbox Code Playgroud)