Chapter 28: Object-Oriented Programming with VBA
1005
The RaiseEvent statement includes a value for the event argument:
RaiseEvent ProductSold(UnitsSold)
Event declarations may include multiple arguments and can pass any valid VBA data type, includ-
ing complex data such as recordsets and other objects.
The ability to pass data through event arguments is an incredibly powerful tool for developers. A
class module can directly communicate with its consumers, passing whatever data and information
is necessary for the consumer to benefit from the class’s resources.
Exploiting Access class module events
You can add custom events to Access forms and to raise those events from code within the form.
Custom events are declared with exactly the same syntax as declaring events within any class mod-
ule and are raised with the RaiseEvent statement. The only tricky part is sinking custom events
raised by a form in another form’s module.
Custom events can be exploited as a way to convey messages and data between forms. Recently, I
responded to a reader’s question about dialog boxes with a relatively lengthy explanation of mod-
ally opening the dialog box, hiding the dialog box when the user was ready to return to the main
form, and then reading a custom property from the hidden dialog box. Although this technique
works well, it requires quite a bit of planning and preparation.
The dialog box operation can be more simply implemented by adding a custom event to the dialog
form that is raised by the dialog form and sunk by the main form. Information entered by the user
on the dialog form is passed to the main form as an event argument. The event is raised when the
user closes the dialog form and the information passed as the event argument is captured by the
main form. There is no need for the main form to close or otherwise manage the dialog form.
Let’s start with the dialog form that raises a custom event. The dialog form is shown in
Figure 28.15.
FIGURE 28.15
This form uses a custom event to pass data back to the main form.
The user types something into the text box and clicks either OK or Cancel. The OK button passes
the text box’s contents to the main form, while the Cancel button passes a “No data” message,
indicating that the user dismissed the dialog box without entering any data.