AutoExec
MacroDoCmd
ObjectAutoExec
Macro to the Time and Billing ApplicationAlthough you may not prefer to use macros to develop the routines that control your applications, macros in Access 2007 play a major role in the development process. Available in Microsoft Office Access 2007 are embedded macros. Rather than appearing in the Navigation Pane as a separate object, an embedded macro is part of the object to which it is associated. When you modify an embedded macro, it does not affect any other macros or objects in the database. Because you can prevent embedded macros from performing certain potentially unsafe operations, they are trusted. In addition to their other benefits, using Access 2007 macros can often help you get started with developing applications—because these macros can be converted to VBA code. This means you can develop part of your application using macros, convert the macros to VBA code, and then continue developing your application. Although I don’t recommend this approach for serious developers, it offers a great jump-start for those new to Access or Windows development in general.
To create a macro, click to select the Create tab. Then select Macro from the Other group. The Macro Design window shown in Figure 7.1 appears. In this window, you can build a program by adding macro actions, arguments, names, and conditions to the macro.
Figure 7.1. The Macro Design window, showing the macro Action, Arguments, and Comment columns.
Macro actions are like programming commands or functions. They instruct Access to take a specific action, for example, to open a form. Macro arguments are like parameters to a command or function; they give Access specifics on the selected action. For example, if the macro action instructs Access to open a form, the arguments for that action tell Access which form should be opened and how it should be opened (Form, Design, or Datasheet view or Print Preview). Macro names are like subroutines, and several subroutines can be included in one Access macro. Each of these routines is identified by its macro name. Macro conditions allow you to determine when a specific macro action will execute. For example, you might want one form to open in one situation and a second form to open in another situation.
As mentioned, macro actions instruct Access to perform a task. You can add a macro action to the Macro Design window in several ways. One method is to click in a cell in the Macro Action column and then click to open the drop-down list. A list of all the macro actions appears, as in Figure 7.2. Select the one you want from the list, and it’s instantly added to the macro. Use this method of selecting a macro action if you aren’t sure of the macro action’s name and want to browse the available actions.
Figure 7.2. The Macro Action drop-down list, showing all the available macro actions.
After you have been working with macros for a while, you will know which actions you want to select. Rather than open the drop-down list and scroll through the entire list of actions, you can click a cell in the Action column and then start typing the name of the macro action you want to add. Access will find the first macro action beginning with the character(s) you type.
The OpenTable
, OpenQuery
, OpenForm
, OpenReport
, and OpenModule
actions are used to open a table, query, form, report, or module, respectively. You can fill in all these actions and associated arguments quite easily with a drag-and-drop technique:
frmClients
form onto the Macro Design window.
Figure 7.3. The Macro Design window after the frmClients
form was dragged and dropped on it.
Dragging and dropping a table, query, form, report, or module onto the Macro Design window saves you time because all the macro action arguments are automatically filled in for you. Notice in Figure 7.3 that six action arguments are associated with the OpenForm
action: Form Name
, View
, Filter Name
, Where Condition
, Data Mode
, and Window Mode
.
Three of the arguments for the OpenForm
action have been filled in: the name of the form (frmClients
), the view (Form), and the window mode (Normal). Macro action arguments are covered more thoroughly in the next section.
As mentioned, macro action arguments are like command or function parameters; they give Access specific instructions on how to execute the selected macro action. The available arguments differ depending on what macro action has been selected. Some macro action arguments force you to select from a drop-down list of appropriate choices; others allow you to enter a valid Access expression. Macro action arguments are automatically filled in when you click and drag a Table, Query, Form, Report, or Module object to the Macro Design window. In all other situations, you must supply Access with the arguments required to properly execute a macro action. To specify a macro action argument, follow these five steps:
Form Name
argument associated with the OpenForm
action. Because the selected argument is Form Name
, the names of all the forms included in the database are displayed in the drop-down list.
Where Condition
argument of the OpenForm
action, for example. After you click in the Where Condition text box, an ellipsis appears. If you click on the ellipsis, the Expression Builder dialog box is invoked, as shown in Figure 7.5.
Figure 7.5. The Expression Builder dialog box allows you to easily add complex expressions to your macros.
Figure 7.6. The completed expression for the Where
argument of the OpenForm
action.
Remember that each macro action has different macro action arguments. Some of the arguments associated with a particular macro action are required, and others are optional. If you need help on a particular macro action argument, click in the argument and Access gives you a short description of that argument. If you need more help, press F1 to see Help for the macro action and all its arguments, as shown in Figure 7.7.
Figure 7.7. Help on the OpenForm
action.
Macro names are like subroutines; they allow you to place more than one routine in a macro. This means you can create many macro routines without having to create several separate macros. You should include macros that perform related functions within one particular macro. For example, you might build a macro that contains all the routines required for form handling and another that has all the routines needed for report handling.
Only two steps are needed to add macro names to a macro:
Figure 7.8. The Macro Name column allows you to create subroutines within a macro.
OpenFrmClients
, OpenFrmTimeCards
, and CloseAnyForm
. The OpenFrmClients
subroutine opens the frmClients
form, showing all the clients added in the past 30 days. The OpenFrmTimeCards
subroutine opens the frmTimeCards
form, and the CloseAnyForm
subroutine displays a message to the user and then closes the active form.
The Macro Name column is a toggle. You can hide it and show it at will, without losing the information in the column.
At times, you want a macro action to execute only when a certain condition is true. Fortunately, Access allows you to specify the conditions under which a macro action executes:
Figure 7.10. You can designate the condition under which a macro action executes in the Condition column of a macro.
The macro pictured in Figure 7.11 evaluates information entered on a form. The CheckBirthDate
subroutine evaluates the date entered in the txtBirthDate
text box. Here’s the expression entered in the first condition:
DateDiff("yyyy",[Forms]![frmPersonalInfo]![txtBirthDate],Date()) Between 25 And 49
Figure 7.11. An example of a macro containing conditions.
This expression uses the DateDiff
function to determine the difference between the date entered in the txtBirthDate
text box and the current date. If the difference between the two dates is between 25 and 49 years, a message box is displayed indicating that the person is over a quarter century old.
The ellipsis on the second line of the CheckBirthDate
subroutine indicates to Access that the macro action should be executed only if the condition entered on the previous line is true. In this case, if the condition is true, the macro is terminated.
If the first condition isn’t satisfied, the macro continues evaluating each condition in the subroutine. The CheckBirthDate
subroutine displays an age-specific message for each person 25 years of age and older. If the person is younger than 25, none of the conditions is met, and no message is displayed.
The CheckGender
subroutine works a little bit differently. It evaluates the value of the optGender
option group. One of the first two lines of the subroutine execute, depending on whether the first or second option button is selected. The third line of the subroutine executes regardless of the Option Group value because no ellipsis is entered in the macro action’s Condition column. If no ellipsis is found on any line of the subroutine, the macro action executes unconditionally. If an ellipsis were placed before the line, the macro action would execute only if the value of OptGender
was 2
.
You have learned quite a bit about macros but haven’t yet learned how to execute them. This process varies depending on what you’re trying to do. You can run a macro from the Macro Design window or by double-clicking the macro in the Macros Group of the Navigation Pane, triggered from a Form or Report event, or invoked by selecting a custom ribbon button. The first three methods are covered in the following sections, but invoking a macro from a custom ribbon is covered in Chapter 23, “Working with and Customizing Ribbons.”
A macro can be executed easily from the Macro Design window. Running a macro without subroutines is simple: Just click Run in the Tools group of the Design tab. Each line of the macro is executed unless conditions have been placed on specific macro actions. After you click the Run button of mcrOpenClients
(shown in Figure 7.12), the frmClients
form is opened.
Figure 7.12. Running a macro from the Macro Design window.
From Macro Design view, you can run only the first subroutine in a macro. To run a macro with subroutines, click Run from the Tools group on the Design page to execute the first subroutine in the macro. As soon as the second macro name is encountered, the macro execution terminates. The section “Triggering a Macro from a Form or Report Event,” later in this chapter, explains how to execute subroutines other than the first one in a macro.
To run a macro from the Macros group of the Navigation Pane, follow these two steps:
If the macro you execute contains macro names, only the macro actions with the first subroutine are executed.
Chapter 9, “Objects, Properties, Methods, and Events Explained,” introduces the concept of executing code in response to an event. Here, you learn how to associate a macro with a command button.
The form in Figure 7.13 illustrates how to associate a macro with the Click
event of a form’s command button. Four steps are needed to associate a macro with a Form or Report event:
cmdCheckGender
command button is selected.Click
event of the command button is selected.mcrPersonalInfo
and the macro name CheckGender
have been selected. Notice the period between the name of the macro and the name of the macro name subroutine. The period is used to differentiate the macro group (mcrPersonalInfo
, in this case) from the macro name (CheckGender
, in this example).Figure 7.13. Associating a macro with a Form or Report event.
Table 7.1. The mcrPersonalInfo Macro
You have learned how to create a macro, add macro actions and their associated arguments, create macro subroutines by adding macro names, and conditionally execute the actions in the macro by adding macro conditions. However, after you have created a macro, you might want to modify it. First, you must enter Design view for the macro:
When the design of the macro appears, you’re then ready to insert new lines, delete existing lines, move the macro actions around, or copy macro actions to the macro you’re modifying or to another macro.
To insert a macro action, follow these steps:
To insert multiple macro actions, follow these steps:
Follow these steps to delete a macro action:
Follow these steps to delete multiple macro actions:
You can move macro actions in a few ways, including dragging and dropping and cutting and pasting. To move macro actions by dragging and dropping, follow these steps:
If you accidentally drag and drop the selected macro actions to an incorrect place, use the Undo button on the Quick Access toolbar to reverse your action.
To move macro actions by cutting and pasting, follow these steps:
Don’t click the Macro Action Selector of the row where you want to insert the cut macro actions unless you want to overwrite the macro action you have selected. If you don’t click to select the Macro Action Selectors, the cut lines are inserted into the macro without overwriting any other macro actions; if you click to select Macro Action Selectors, existing macro actions are overwritten.
Macro actions can be copied within a macro or to another macro. Follow these steps to copy macro actions within a macro:
Follow these steps to copy macro actions to another macro:
Creating an embedded macro is similar to creating a standard macro. The main difference is that the macro is embedded in the object with which it is associated and does not appear in the list of macros in the Navigation Pane. Here’s how to create an embedded macro:
Figure 7.15. Use the property sheet to associate a macro with the event of an object.
On Click
event is selected.Figure 7.16. The Choose Builder dialog box enables you to specify that you want to build a macro.
btnHello: On Click
, indicating that the macro is associated with the On Click
event of btnHello
.
Figure 7.17. The macro that you create is associated with the appropriate event of the designated object.
Figure 7.18. Your macro commands appear just like macros in earlier versions of Access.
Figure 7.19. If you save your changes, Access embeds the macro in the object.
There are two main major improvements to Access 2007 macros. The first is the introduction of error handling, and the second is the introduction of variables. Notice the OnError
macro action in Figure 7.20. The example branches to a macro named ErrorHandler
in the case of an error. Unlike previous versions of Access, where error handling in macros was virtually nonexistent, the new OnError
macro action provides similar error handling to that of VBA code.
Figure 7.20. The OnError
macro action provides similar error handling to that of VBA code.
Another exciting addition to Access 2007 macros is the introduction of variables. The new SetTempVar
macro action enables you to create a variable and assign it a value. Figure 7.21 provides an example. Notice in the figure that the macro uses the SetTempVar
action to create a variable called CurrentDate
and assign it the value returned from the built-in Date()
function.
Figure 7.21. You use the SetTempVar
action to create a temporary variable in a Microsoft Office Access 2007 macro.
Just as it’s useful to document any program, it’s also useful to document what you’re trying to do in your macro. These comments can be used when you or others are trying to modify your macro later. They can also be used as documentation because they print when you print the macro.
To add a comment to a macro, click in the Comment column of the macro and begin to type. Figure 7.22 shows a macro with comments. As you can see in Figure 7.23, these comments appear in the printed macro.
Figure 7.22. Adding comments to a macro.
Figure 7.23. Comments included in the printed macro.
Although Access doesn’t offer very sophisticated tools for testing and debugging your macros, it does give you a method for stepping through each line of a macro:
mcrPersonalInfo
, the Condition evaluates to False
, and the Action Name is MsgBox
. The MsgBox
arguments are You Are Over a Quarter Century Old
, Yes
, and Information
.
Figure 7.24. In the Macro Single Step dialog box, you can view the macro name, condition, action name, and arguments for the current step of the macro.
As you can see, although Microsoft supplies some tools to help you debug your macro, you will probably agree that they are limited compared to the tools available with the VBA debugger. (See Chapter 16, “Debugging: Your Key to Successful Development.”) That’s one reason why many developers prefer to develop applications by using VBA code.
The Single Step button in the Tools group of the Design tab is a toggle. After you activate Step Mode, it’s activated for all macros in the current database and all other databases until you either turn off the toggle or exit Access. This behavior can be quite surprising if you don’t expect it. You might have invoked Step Mode in another database quite a bit earlier in the day, only to remember that you forgot to click the toggle button when some other macro unexpectedly goes into Step Mode.
Macros aren’t always the best tools for creating code that controls industrial-strength applications because they’re limited in some functionality. Access macros are limited in the following ways:
Sometimes you will create a macro, later to discover that you want to convert it to VBA code. Fortunately, Access 2007 comes to the rescue. You can easily convert an Access macro to VBA code; after the macro has been converted to VBA code, the code can be modified just like any VBA module. Follow these six steps to convert an Access macro to VBA code:
Figure 7.25. The macro Save As dialog box allows you to save a macro as a Visual Basic module.
Figure 7.26. Use the Convert Macro dialog box to indicate whether error handling and comments will be added to the Visual Basic module.
Converted Macro:
followed by the name of the macro. Click Design to view the results of the conversion.Figure 7.27 shows a macro that’s been converted into distinct subroutines, one for each macro name. The macro is complete with logic, comments, and error handling. All macro conditions are converted into If...Else...End If
statements, and all the macro comments are converted into VBA comments. Basic error-handling routines are automatically added to the code.
Figure 7.27. A converted macro as a module.
When you convert a macro to a Visual Basic module, the original macro remains untouched. Furthermore, all the objects in your application will still call the macro. To effectively use the macro conversion options, you must find all the places where the macro was called and replace the macro references with calls to the VBA function.
AutoExec
MacroWith Access 2007, you can use either an AutoExec
macro or Startup options to determine what occurs when a database is opened. Using an AutoExec
macro to launch the processing of your application is certainly a viable option.
Creating an AutoExec
macro is quite simple; it’s just a normal macro saved with the name AutoExec
. An AutoExec
macro usually performs tasks such as hiding or minimizing the Navigation Pane and opening a Startup form or switchboard. The macro shown in Figure 7.28 hides the Navigation Pane, displays a welcome message, and opens the frmClients
form.
Figure 7.28. An example of an AutoExec macro.
When you’re opening your own database to make changes or additions to the application, you probably won’t want the AutoExec
macro to execute. To prevent it from executing, hold down your Shift key as you open the database.
DoCmd
ObjectMost macro commands can be performed in VBA code by using the DoCmd
object. The macro action becomes a method of the DoCmd
object, and the arguments associated with each macro action become the arguments of the method. For example, the following method of the DoCmd
object is used to open a form:
The OpenForm
method of the DoCmd
object that opens the form appears as the first argument to the method. The second argument indicates the view in which the form is opened. The third and fourth arguments specify a filter and Where
condition, respectively. The fifth argument of the OpenForm
method specifies the Data mode for the form (Add, Edit, or Read Only). The sixth argument indicates the Window mode (Normal, Hidden, Minimized, or Dialog).
Notice the intrinsic constants used for the OpenForm
arguments; they help make the code more readable. You can find them in the Help for each DoCmd
method.
AutoExec
Macro to the Time and Billing ApplicationIn Chapter 10, “Advanced Form Techniques,” you will learn how to add a switchboard to your application. For now, you’ll build an AutoExec
macro that acts as the launching point for your application. The macro will start the application by hiding the Navigation Pane, displaying a message to the user, and opening the frmClients
form.
Build the macro shown in Figure 7.28. Start by opening a new macro in Design view. Set the first action of the macro to RunCommand
and then set the DatabaseCommand
argument to WindowHide
. This will hide the Navigation Pane when it’s run. Set the second action of the macro to MsgBox
and set the message to Welcome to the Client Billing Application
. Set Beep to No
, the Type to Information
, and the Title to Welcome
. The final action of the macro opens the frmClients
form. Set the action to OpenForm
and set the FormName to frmClients
. Leave the rest of the arguments at their default values.
Close and reopen the database. The AutoExec
macro should automatically execute when the database is opened. Close the database and open it again, holding down the Shift key to prevent the macro from executing.
Many end users try to develop entire applications by using macros. Although this is possible, you will generally want to use a combination of macros and modules to build your applications.
New to Microsoft Office Access 2007 are embedded macros. You associate these macros with a specific event. Also new to Microsoft Office Access 2007 are the capability to add error handling to a macro and the capability to include variables in a macro. These three new features make macros a much more viable choice for application development.
3.15.151.21