vba trigger on variable code example

Example: vba trigger on variable

' Adds a user defined trigger (OnChange event) on a class attribute
' Msgbox when Name (clsMyClass) is changed
' Add class module clsMyClass:
Private WithEvents mName As clsWithEvents
Private Sub mName_OnChange(ByVal pValue As String)
    MsgBox "Value changed to " & pValue
End Sub
Public Property Get Name() As clsWithEvents
    Set Name = mName
End Property
Public Property Let Name(pClsName As clsWithEvents)
    Set mName = pClsName
End Property

'Add class module clsWithEvents
Public Event OnChange(ByVal pValue As String)
Private mCurrentValue As String
Public Property Get Value() As String
    Value = mCurrentValue
End Property
Public Property Let Value(ByVal pValue As String)
    If mCurrentValue <> pValue Then RaiseEvent OnChange(pValue)
    mCurrentValue = pValue
End Property

' Test in a module:
Sub TestMe()
    Dim cMyClass As New clsMyClass
    Dim cName As New clsWithEvents
    cMyClass.Name = cName
    cName.Value = "New value"   ' Triggers a msgbox
End Sub

Tags:

Misc Example