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 Sub
Responding 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
Sheet
object 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
Sheet
object.Declare
Message
object using WithEvents: ...
Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.