Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 28: Object-Oriented Programming with VBA


1007


Private WithEvents frm As Form_frmDialogForm
Private Sub cmdOpenDialogForm_Click()
Set frm = New Form_frmDialogForm
frm.Visible = True
End Sub
Private Sub frm_FormClosing(Message As String)
txtDialogMessage.Value = Message
End Sub

The dialog form must be declared as a module-level variable behind the main form. The
WithEvents keyword notifies the VBA engine that you want the main form to capture (or sink)
events raised by the frm object.

Also notice that the form’s class name is Form_frmDialogForm. This is the name of the class
module behind frmDialogForm, and it’s the entity that actually raises the event. From the per-
spective of the VBA project driving the application, the form’s surface is just a graphic interface and
has nothing to do with the class module that supplies the logic driving the form.

The WithEvents keyword is almost magical. Once you’ve qualified an object declaration with
WithEvents, the name of the object appears in the drop-down list at the top of the class module,
and the object’s events appear in the right drop-down list (see Figure 28.17).

All Access developers are familiar with how the object drop-down list shows all the controls placed
on the surface of an Access form, as well as an entry for the form itself. In this case, the object
drop-down list shows the form object declared with the WithEvents keyword in addition to
controls on the form’s surface.

In this case, the form object named frm is declared and instantiated, and it’s completely controlled
by the main form. The main form captures the dialog form’s events and uses the data passed
through the FormClosing event. The main form could just as easily reference other properties of
the dialog form.

FIGURE 28.17

The WithEvents keyword enables the main form’s class module to capture events raised by the object.

Free download pdf