[AccessD] CREATE CLASSES AND EVENTS DEMO DATABASE

jwcolby jwcolby at colbyconsulting.com
Mon Feb 9 12:06:16 CST 2009


* Create a blank database
* Create a new form.  Drag and drop one of each of the controls onto the form.  Save the form.
* On the menu click insert / Class module.
* If you haven’t already done so, turn on “require variable declaration”.  Inside the editor, click 
Tools / Options / Editor (tab) and check the “require variables declaration” box.
* Immediately save the module, and name it clsFrm.

* Type the following into the module (or cut and paste):

Private WithEvents mfrm As Form
Private Const cstrEvProc As String = "[Event Procedure]"

The first line declares a private variable called mfrm and tells VBA that this class will SINK 
EVENTS for the form inside of this class.

The second line declares a private constant cstrEvProc and places the text "[Event Procedure]" in 
the constant.

* Next type the following into the module:

Function mInit(lfrm As Form)
     Set mfrm = lfrm
         mfrm.BeforeUpdate = cstrEvProc
End Function

This creates a method of the class called mInit and passes in a form variable called lfrm.

The set statements then saves the lfrm variable passed in into the mfrm variable that we created 
above.

The next statement places the string "[Event Procedure]" into the BeforeUpdate  property of the form 
mfrm.  This requires an explanation.  It turns out that if you have the actual text string "[Event 
Procedure]" (without the quotes) in any event property of any form or control, then that event will 
fire in the class.  You can prove that to yourself by deleting this text in some property of some 
form or control in an existing project, cause that event to fire, and notice that the code no longer 
runs in your code behind form.  Put that text string back and notice that the event code now runs in 
your code behind form.

Pretty easy so far yes?  To reiterate, we have declared a variable and a constant that are PRIVATE 
to the class, meaning that they can only be accessed from inside of the class.  We created a method 
that we can use to pass in a reference or pointer to some form, we have saved that pointer to some 
form passed into this class instance to a variable in the top of our class, and we have placed the 
text "[Event Procedure]" into the BeforeUpdate event property of mfrm.

At this point we have a form, with one of each control on the form.  We also have a class which can 
be instantiated, and passed in a pointer to some form.  The class can save the pointer to the form 
passed in and can activate the form to raise one specific event (BeforeUpdate).

Do this much before we continue.  This should take you just a few minutes to complete.

-- 
John W. Colby
www.ColbyConsulting.com



More information about the AccessD mailing list