VBA is described as an Event driven programming language. What is meant by this?
Access, like most Windows programs, is an event driven application. This means that nothing happens unless it is in response to some event that has been detected by the application.
The steps are fairly straightforward:
- An event happens
- The event is detected by the application
- The application responds to the event
The Windows OS will automatically detect when an event has occured, like a mouse move, mouse click, form load, etc. If the OS doesn't find a VBA procedure relating to that event it will just go with its default behaviour for that event. The programmer does not need to determine when a particular event happens as Windows does that for you. If you program a procedure to respond to that particular event, then it will override the default behaviour for that event. Therefore, the programmer only needs to code those events where something other than the default behavior should occur. For example, the default behaviour if a button is clicked is that the button gains focus. You only need to code any other tasks you wish to be performed when this event occurs.
Although the obvious event for a button is the Click (On Click) event there are actually 12 possible events associated with a button.
To code an event:
Right click on the object or control you wish to program an event for. Go to properties and go to the Event tab. Choose the event you wish to code e.g. On Click for a button control. Click on the builder button (the one with three dots) and select Code Builder from the list. This will open the Visual Basic Editor with the opening and closing lines of the event procedure already coded. Everything you put between these two lines will execute when the button is clicked.
Every form and report object can have events programmed on them, as can all the controls in those same forms and reports.
Below are some of the more common events with details of when they occur:
- Event Found on Occurs when
-
On Change Controls on Form after contents of control change
-
On Click Forms, controls and when user clicks mouse over control
-
sections on form
-
On Close Forms, Reports after form or report closes
-
On Current Forms when form is open or requeried and
-
when focus moves to a different record
-
but before new record is displayed
-
On Dbl Forms, controls and when mouse button is double clicked
-
Click sections on form
-
On Delete Forms when user attempts to delete a record
-
On Dirty Forms when user updates data on current record
-
but before record is saved
-
On Error Forms, Reports when a runtime database engine error occurs
-
but not a VBA error
-
On Mouse Forms, controls and when the mouse pointer moves over an object
-
Move sections on form
-
On Mouse Forms, controls and when the user releases the mouse button
-
Up sections on form
There are many more events but these should get you started.