Learn Access 2003 VBA with The Smart Method
62
www.LearnAccessVBA.com
Lesson 3-3: Understand events
What are events.
Consider a telephone. Somebody could call the telephone at any time.
The telephone doesn’t know when it is going to happen, or even whether
it will ever happen at all.
Suppose somebody does call, the telephone might respond by ringing its
bell.
In object-speak we’d say that the telephone object had responded to its
SomebodyCalling event by invoking its RingBell method.
1
Open a new blank database and save it as VBACode.mdb.
2
Create a new form in Design View and save it as frmTest.
3
Add a command button to your new form dismissing the
Command Button Wizard by clicking its Cancel button.
4
Set some of the Command Button’s properties.
A Command Button (and every other control) is an object and will
have its own set of properties, methods and events. It’s important
that you get into this mindset in order to understand how VBA
and Access interact.
To view the Command Button’s property sheet right-click it and
select Properties from the shortcut menu.
Set the Command Button’s Name property to cmdPressMe and the
Caption property to &Press Me.
Let’s now consider an event that might happen in the life of a
command button.
The most important thing that can happen to the command button
is that somebody might click it. This is referred to in object
terminology as the command button’s Click event.
5
Right-click the command button and choose Code Builder
from the shortcut menu.
The Choose Builder dialog appears.
Session3
pg_0002
Session Three: The Object-Orientated Paradigm
© 2007 The Smart Method Ltd
63
6
Choose Code Builder from the dialog.
The VBA editor appears with code for the Command Button’s
Click event handler displayed.
The command button does have other events but the Click event is
shown by default as it is the most important event for this control.
7
Browse the Command Button’s other events.
There’s plenty of other less obvious things that can happen to a
command button. In all there are twelve events.
Open the VBA editor and select the pulldown list arrow at the top
right of the code window. Browse the possible events for a
Command Button. You should be able to guess what most of them
mean.
8
Add the following code to the Command Button’s Click
event:
Private Sub cmdPressMe_Click()
Beep
End Sub
9
Test the Command Button’s event handler.
Close the Visual Basic editor and display the form in Form View.
Click the button (make sure that your computer’s sound is
switched on). When you click the button the Click event is
triggered. The code you added causes the computer to beep.