Access VBA Macro Programming

(Joao Candeias) #1
Using VBA on Forms

Up till now, this chapter has looked at how to build forms and bind the controls to the underlying
data. Although this is not directly connected with VBA, it is a very necessary part of building
an Access application.
However, forms also have their own modules and there is a whole event-driven structure
both for the form and the controls on it. As you have already seen, the form and controls have
a rich collection of properties, which allows an enormous amount of manipulation, letting
you change what the user sees according to certain circumstances.


Opening Your Form in VBA


The initial form in an Access application is usually opened by setting the Display form
property of the Current Database. You do this by clicking the File tab in ribbon and clicking
the Access Options button at the bottom of the pop-up.
In the next pop-up, select Current Database in the pane on the left-hand side. In the
Application options section, there is a drop-down for Display Form that lists all the available
forms. Select your opening form, and this will automatically load when the database opens.
To load other forms, use the OpenForm method of the DoCmd object (see Chapter 16 for
more information on this object).


DoCmd.OpenForm _
(FormName,View,FilterName,WhereCondition,DataMode,WindowMode,OpenArgs)


The FormName is a required parameter, but the others are optional:

 View An acFormView constant that specifies the view that the form will open in.
This is acNormal by default.
 FilterName The name of a query in the current database.
 WhereCondition An SQL WHERE clause without the word WHERE.
 DataMode An acFormOpenDataMode constant that specifies the data entry mode for
the form.
 WindowMode An acWindowMode constant that specifies the window that the form
opens in.
 OpenArgs This sets the form’s OpenArgs property.

You can also use the Close method of the DoCmd object to close the form when it is finished.

Using Events

When a user opens your form, browses through it, deletes records, edits records, adds records,
and closes the form, they are constantly firing off events that can be put to use in VBA. Some of
these events can be confusing when they are fired off and sometimes it is a good idea to put a
simple message box into each event so you can see when it actually happens.


Chapter 9: Forms and Reports 111

Free download pdf