The 'DoCmd' Object: Performing Macro Actions

The Access environment is rich with objects that have built-in properties and methods. By using VBA code, you can modify properties and execute methods. One of the objects available in Access is the DoCmd object, which is used to execute macro actions in Visual Basic procedures. You execute the macro actions as methods of the DoCmd object. The syntax looks like this:

DoCmd.ActionName [arguments]

Here's a practical example:

DoCmd.OpenReport strReportName, acPreview

The OpenReport method is a method of the DoCmd object that runs a report. The first two parameters that the OpenReport method receives are the name of the report you want to run and the view in which you want the report to appear (Preview, Normal, or Design). The name of the report and the view are both arguments of the OpenReport method.

Most macro actions have corresponding DoCmd methods, but some don't. The macro actions that don't have corresponding DoCmd methods are AddMenu, MsgBox, RunApp, RunCode, SendKeys, SetValue, StopAllMacros, and StopMacro. The SendKeys method is the only one of these methods that has any significance to you as a VBA programmer. The remaining macro actions either have no application to VBA code, or you can perform them more efficiently by using VBA functions and commands. The VBA language includes a MsgBox function, for example, that's far more robust than its macro action counterpart.

Many of the DoCmd methods have optional parameters. If you don't supply an argument, the compiler assumes the argument's default value. You can use commas as place markers to designate the position of missing arguments, as shown here:

DoCmd.OpenForm "frmOrders", , ,"[OrderAmount] > 1000"

The OpenForm method of the DoCmd object receives seven parameters; the last six parameters are optional. In the example, I have explicitly specified two parameters. The first is the name of the form ("frmOrders"), a required parameter. I have omitted the second and third parameters, meaning that I'm accepting their default values. The commas, used as place markers for the second and third parameters, are necessary because I am explicitly designating one of the parameters following them. The fourth parameter is the Where condition for the form, which I am designating as the record in which OrderAmount is greater than 1,000. I have not designated the remaining parameters, so Access uses the default values for these parameters.

If you prefer, you can use named parameters to designate the parameters that you are passing. Named parameters can greatly simplify the preceding syntax. With named parameters, you don't need to place the arguments in a particular order, nor do you need to worry about counting commas. You can modify the preceding syntax to the following:

DoCmd.OpenForm FormName:="frmOrders", WhereCondition:= 
"[OrderAmount] > 1000"

    Part III: Creating Your Own Database and Objects
    Part V: Advanced Topics