Chapter 28: Object-Oriented Programming with VBA
1003
RaiseEvent InvalidSupplierID()
End If
End Property
The SupplierName property raises the InvalidSupplierID under two different situations:
when the SupplierID is zero or a negative number, and when the DLookup function fails to
locate a record in the Suppliers table.
There is no requirement that consumer code respond to events raised by class modules. In fact,
events are very often ignored in application code. I doubt you’ve ever written code for every single
event raised by an Access TextBox control, and custom events raised from class modules are no
different.
But, again, that’s one of the nice things about object-oriented programming: You can add as many
events as needed by your classes. Consumer code working with your classes can ignore irrelevant
events and trap only those events that are important to the application.
Trapping custom events
Just about the only place where event-driven programming with Access classes becomes tricky is
when it’s time to capture events (also called sinking events) in consumer code. There are a number
of rules governing event consumption:
l (^) The class hosting events must be declared within another class module. It shouldn’t
be surprising that events can only be captured by code within class modules. After all,
class modules are special critters and have capabilities beyond simple code modules.
You’ve never seen a stand-alone VBA code module directly respond to events raised by
controls on an Access form, so there’s no reason to expect a plain code module to be able
to consume events raised by the classes you add to an application.
However, a plain code module can very well create and use objects derived from class
modules. It’s just that VBA code modules can’t capture events raised from class modules.
This requirement is not quite as onerous as it first appears. After all, every form and report
module is a class module. That means that forms and reports are ready-built for consum-
ing the events thrown by your class modules.
l The object variable created from the class must be module-level and can’t be
declared within a procedure. There’s no way to capture an event from within a proce-
dure. Procedures know nothing about objects, and there’s no provision for hooking a
locally declared object variable to its events.
When you look at the class module behind a form, it becomes obvious why object vari-
ables must be module-level before their events can be sunk by consumer code. You’ve
seen the typical Access form module (shown in Figure 28.14). Notice what appears in the
code module’s event list when an object variable has been declared with the WithEvents
keyword.