Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 28: Object-Oriented Programming with VBA


1001


set through the SupplierID Property Let procedure. The If...End If at the top of this
procedure handles cases where the m_SupplierID variable has not been properly set to a value
greater than zero.


So far, so good. But, what happens if the SupplierID can’t be found in the supplier table? The
only way the class’s consumer can determine that the supplier does not exist is by examining the
value of the SupplierName property. If the SupplierName property is an empty string, the
consumer can assume the supplier cannot be found in the supplier table and notify the user
accordingly.


The problem with this scheme is that a lot of work is left up to the consumer. The consumer must
first set the SupplierID property, then ask for the SupplierName property, and then finally
examine SupplierName to see if a nonzero-length string was returned by the SupplierName
Property Get.


One of the basic tenets of object-oriented programming is that a class module should encapsulate
most, if not all, of the processing required by the entity represented by the class. In the case of the
Product class, a consumer shouldn’t be required to examine a property’s return value to verify its
validity. The class should notify the consumer when a problem (such as missing or invalid data)
arises within the class.


And, that’s one of the primary purposes of events. The InvalidSupplierID event is invoked
whenever the class determines that a problem exists with the SupplierID value supplied by the
consumer code.


Creating custom events


Events must be declared within a class module. Although an event declaration may occur anywhere
within a VBA module, it only makes sense to position event declarations near the top of the module
where they’re easily seen by other developers. An event declaration is actually quite simple:


Public Event InvalidSupplierID()

That’s all there is to an event declaration. The Public keyword is needed, of course, to expose
the event to the class’s consumers. In effect, the Public keyword adds the event to the
class’s interface. The Event keyword, of course, specifies that the declaration’s identifier —
InvalidSupplierID — is an event and should be managed by VBA’s class module hosting
mechanism.


You might recall that I’ve asserted that class modules were special in a number of regards. Events
are clearly one of the special characteristics of VBA class modules.


A quick look through the Object Browser at the class module (see Figure 28.13) shows that the
class’s interface does, indeed, include the InvalidSupplierID event.

Free download pdf