Raise Events
I mentioned earlier that, unlike modules, classes can include events
. Classes define events using an Event statement and then raise those events using RaiseEvent. For example, the following additions (in bold) create an event that occurs whenever a message is shown or sent using the Message class:
' Message class
Public Event OnShow(arg As MessageType)
' Show method: displays the message.
Public Sub Show(Optional icon As IconType = -1)
If (icon = -1) Then icon = Me.icon
MsgBox value, icon, Title
RaiseEvent OnShow(MessageType.MessageBox)
End Sub
' Send method: sends the message via email.
Public Sub Send(Optional ToAddress As String)
Dim msgToSend As String, result As Double
If ToAddress = "" Then ToAddress = m_Recipients
msgToSend = "mailto:" & ToAddress
msgToSend = msgToSend & "?SUBJECT=" & Title
msgToSend = msgToSend & " &BODY=" & value
ThisWorkbook.FollowHyperlink msgToSend, , True
RaiseEvent OnShow(Email)
End SubResponding to the OnShow event from within code that uses the Message class requires a few steps:
Write your code in a class—you can’t intercept events from a module. For example, write your code in a
Sheetobject within Visual Basic.Declare the object at the class level using
WithEvents.Initialize that object by creating an instance of the class.
Create an event procedure to respond to the event.
The following sample illustrates the steps to using the OnShow event from a Sheet object:
Create code in
Sheetobject.Declare
Messageobject using WithEvents: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access