Part IV: Professional Database Development
1004
FIGURE 28.14
The WithEvents keyword instructs VBA to watch for events raised from the object’s
class module.
As you’d expect, selecting an event from the Product object’s event list opens a new
event procedure, enabling you to write code in response to the event. The Product_
InvalidSupplierID event procedure notifies the user whenever the Product class
determines that the SupplierID value cannot be used by the class.
Obviously, the code in the event procedure runs whenever the corresponding event is
raised from the object’s class module. The consumer doesn’t have to explicitly check the
value returned by the SupplierName property. Instead, the event procedure linked to
the InvalidSupplierID handles the event and takes appropriate action.
Also, because the same event can be raised from multiple places within the class module,
a single event procedure may handle many different situations related to a single problem
within the class module.
I suspect that, behind the scenes, Access does exactly the same thing for built-in objects
such as text boxes and command buttons. As soon as you add a control to an Access form,
you’re able to add code to event procedures hooked into the control’s events.
l The object variable declaration must include the WithEvents keyword. The keyword
WithEvents is how Access knows that it needs to monitor events raised by the class to
enable you to include code to react to the events.
Passing data through events
You probably noticed that the event declaration example given earlier in this chapter included a set
of empty parentheses:
Public Event InvalidSupplierID()
What may not be obvious is that event arguments may be added within the parentheses:
Public Event ProductSold(Quantity As Integer)