Changing a variable raises an event
Is it possible to trigger an event by changing a variable? For example.
This will trigger an event
Dim t As Integer
Dim Fire As Boolean
Private Sub Test
t = 0
Fire = True
IIf Fire, t=1, t=2
End sub
In event handler
Select Case t
Case 0
'Do something
Case 1
'Do something
Case 2
'Do something
Case 3
'Do something
...
Google fires event handlers and uses class modules, but I can't wrap my head around it.
source to share
Yes it is possible. However, you will need an object oriented approach. First you need to define the class in which the events you want to connect to are raised. Second, you will need a class that actually handles the event, as you cannot use event handlers in a regular module. Third, in your normal module, you can simply use these classes.
Here's a simple example: Create a class module named ClassWithEvent. Enter the following code:
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
Then create a class that can handle events generated by that class. Name this cool module "ClassHandlesEvent". Paste the following code into it:
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
Then, in a regular module, instantiate the ClassWithEvent class and pass it as a property to the class that handles them.
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
source to share