Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change in variable triggers an event

Is triggering an event via a change in variable possible? For example.

This would trigger the 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 the event handler

Select Case t
    Case 0
       'Do something
    Case 1
       'Do something            
    Case 2
       'Do something
    Case 3
       'Do something
    ...   

Google brings up Event handlers, and using class modules but I am unable to wrap my head around it.

like image 519
Quint Avatar asked Mar 08 '23 22:03

Quint


1 Answers

Yes this is possible. However, you'll need an Object Oriented approach. You first need to define a class that raises the events you wish to hook into. Secondly you'll need a class that actually handles the event, since you can not use event handlers in a regular module. Thirdly, in your regular module you can then just use these classes.

Here's a simple example: Create a class module named "ClassWithEvent". Place 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

Next, create the class that can handle the events raised by this class. Name this Class Module "ClassHandlesEvent". Place the following code in 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

Next, in a regular module, instantiate your ClassWithEvent and pass this one 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
like image 88
Rik Sportel Avatar answered Mar 16 '23 23:03

Rik Sportel