16 Connecting Macros to
Forms and Tables
If all you do with macros is launch them from the navigation pane, you’re missing out on the real fun. Macros become far more powerful when you attach them to forms and tables and use Access events to run them automatically when some- thing important happens. For example, you can use events to run an email-sending macro when someone clicks a button, or to trigger a data-checking macro when someone edits a field.
In this chapter, you’ll start by learning how you can plug your macros into forms and controls and trigger them with Access events. It’s time well spent, because you’ll use almost the same approach to hook up Visual Basic code in Chapter 17. Next, you’ll see how to build smarter macros that evaluate conditions and make decisions.
Finally, you’ll connect a macro to a table, so Access runs the macro when a specific type of editing action takes place.
Macro-Powered Forms
The slickest macros work with the forms in your database. Using this combination, you can create macros that fire automatically when something happens (like when a button is clicked or a record is changed). You can also build much more flexible macros that don’t have fixed argument values—instead, they can read the data they need from the text boxes on a form.
In the following sections, you’ll learn how to help macros and forms come together.
Macro-Powered Forms
Understanding Events
So far, you’ve been running macros the hard way: by finding the ones you want in the navigation pane, and then launching them by hand. But in a well-oiled data- base, macros seldom play an upfront role. Instead, they hide behind the scenes until they’re sparked into action. You could create a macro that’s triggered when you click a button, open a form, or make a change in a text box. These triggers are known as events.
A form has three types of events:
• Control events. These events are the most useful. They happen when you do something with a control. For example, when you click a button, it fires an On Click event. (This is a great time to perform just about any action.) When you change a value in a text box, you get an On Change event. (This is a good time to check that the text makes sense by using your crafty validation code.) You’ll notice that most event names start with the word “On”.
Note: Many controls have the same events. If you have two text boxes and a button on your form, then they all have an On Click event. However, Access isn’t confused, because it keeps track of what event hap- pens, and what control it happens to.
• Section events. As you learned earlier, forms are divided into sections so you can separate the header and footer content from the rest of the record. Each sec- tion has a few of its own events, which fire when you move the mouse around (On Mouse Move), or click somewhere on a blank space (On Click). These events tend to be less useful for macro programmers.
• Form events. A long list of more general events relate to the form. This list includes events that fire when the form is first opened (On Open) and when it’s closed (On Close), when you move from one record to the next (On Current), and when you complete a data operation like an update (After Update).
To see the list of events for a form’s different parts, follow these steps:
1. Open your form in Design mode.
If the Property Sheet isn’t visible, then show it by choosing Form Design Tools | Design➝Tools➝Property Sheet.
2. Select the item that has the events you want to examine.
You can select an individual control, a section, or a form. If you have trouble clicking on the design surface to select the item you want, then just choose it by name from the drop-down list at the top of the Property Sheet.
3. In the Property Sheet, choose the Event tab.
Now you’ll see the list of events that are provided by the control, as shown in Figure 16-1.
Figure 16-1:
Here are the events for a typical text box. When you click one of the Event boxes, a one-line description of the event appears in the status bar at the window’s bottom- left section. As you can see, right now all the Event boxes are empty, which means there aren’t any attached macros.
The biggest challenge in using events is figuring out which ones to employ. If you take a few seconds exploring the events on your form, you’ll find dozens of events, many that are rarely used or ridiculously specialized. That’s where Table 16-1 fits in—it highlights some of the most useful events for macro programming.
Table 16-1. Useful Events for Macro Programming
Control Event Description
All Controls On Enter Occurs when you move to a control for the first time (either by pressing a key like Tab or by clicking with the mouse).
On Mouse Move Occurs when you move the mouse over the control.
Any Editable
Control On Change Occurs when you modify the value in a control.
Button On Click Occurs when you click a button. Other controls have click events too, but most people are in the habit of click- ing buttons to get things done.
Combo Box On Not In List Occurs when you type in an entry that’s not in the list.
Form On Load Occurs when the form is first opened (and you can initialize it).
On Close Occurs when the form is closed. You can cancel this event if you want the form to stay open.
On Current Occurs when you move to a record (including when you open the form, and then move to the first record).
Macro-Powered Forms
Table 16-1. Useful Events for Macro Programming
Control Event Description
On Dirty Occurs when you make the first change in a record. It’s now in Edit mode.
On Undo Occurs when you back out of Edit mode and cancel your changes (usually, by pressing Esc).
Before Insert, Before Update, Before Del Confirm
Occurs when you’re in the process of applying an insert, update, or delete. You can cancel this event if you don’t like what you see (for example, if you find invalid data).
After Insert, After Update, After Del Confirm
Occurs after the operation is complete. You can’t cancel it any longer, but you may want to react to the change to perform another task or update the information you’re showing.
Note: The update, insert, and delete confirmation events (the last two rows in the table) also apply to any editable control. A text box also uses the Before Update and After Update events to indicate when its value has changed. In Chapter 18 (page 567), you’ll see an example that uses this event to react immediately when a specific field is changed (rather than wait until the entire record is updated).
If you browse the Property Sheet’s Event tab, then you’ll find many more events, in- cluding ones that let you react when someone presses a key, clicks somewhere with the mouse, or moves from one control to the next. You don’t need to worry about all these options right now. Once you’ve learned how to respond to an event with a macro, you’ll be able to deal with just about any event.
Attaching a Macro to an Event
Now that you’ve seen the events that forms and controls offer, it’s time to try hooking up a macro. The basic sequence of steps is easy:
1. Create and save a macro, as described on page 475.
2. Open your form in Design mode, and make sure the Property Sheet is visible.
3. Select a control, a section, or the entire form.
4. In the Property Sheet, choose the Events tab, and then find the event you want to use.
5. In the Event box, click the drop-down arrow, and then choose the macro you want to use.
Figure 16-2 shows an example.
Figure 16-2:
In this example, the On Click event of a button is being connected to the MailResults macro you saw on page 498. Now, whenever you click the button, the MailResults macro runs.
FREQUENTLY ASKED QUESTION
Embedded Macros
I created a macro with the Command Button wizard. How can I edit it?
When you drop a button onto a form, Access fires up the Button wizard, which creates a macro for you (page 431).
The macros that the Command Button wizard creates are embedded macros, which means they’re stored inside the form object. This system has some advantages (for example, you can transfer your form from one database to another without losing the associated macros). It also has a downside—namely, you can’t edit or run the macro independently.
Fortunately, you can still modify your embedded macros (or just take a look at them if you’re curious). The trick is to use the Property Sheet. Here’s how:
1. Select the control that uses the macro (in this case, a button).
2. Find the event that has the attached macro. In the case of the button, it’s the On Click event. You’ll see the text “[Embedded Macro]” in the Event box, rather than a macro name.
3. Click once inside the Event box. The ellipsis (…) but- ton appears next to it.
4. Click the ellipsis button to edit the embedded macro in the familiar macro builder.
Reading Arguments from a Form
In Chapter 15, you saw macros that could search for records, print reports, and email data. In all of these cases, the macro arguments were fixed values—in other words,
Macro-Powered Forms
you type them in exactly, and they never change. On page 496, you saw a macro that searched for the text “hay.” Convenient as this macro is, you can’t reuse it to search for anything else. If you want to dig up different text, then you need to create a whole new macro.
To make more flexible macros, you can use an expression instead of a fixed value.
You’ve already used expressions extensively in the past (see page 217 for examples with queries, page 353 with reports, and page 422 with forms), so you won’t have any problem building basic expressions that combine text, add numbers, and use Access functions. But when you’re creating a macro, the most useful expressions are those that can pull a value out of a form. All you need to know is the control’s name.
To see how this process works, you can revise the filtering example shown earlier and create a search form like the one shown in Figure 16-3.
To create this example, you need to start by adding the text box you need for search- ing. Here’s how:
1. Open the form in Design mode.
2. Select Form Design Tools | Design➝Controls➝Text Box, and then draw the text box onto the form.
3. Once it’s there, select it, and then, in the Property Sheet, choose the Other tab.
4. At the top of the Other tab, change the Name property to something more descriptive, like SearchText.
Figure 16-3:
Instead of searching for the word “hay,” this example finds any text you want. The trick? You supply the search text in a text box at the top of the form.
Note: You don’t always have to create a new control. Macros can read the value in any control on your form, including those that are linked to the database record. However, in this example, you need a way to supply some text that isn’t part of a record, so it makes sense to add another text box for that purpose.
Next, it’s time to build the macro. You no longer need the OpenForm action (which you used in the original macro), because you can assume that Access will launch this macro from the already open AnimalTypes form. So the first action you need is GoToControl, with the Control Name argument set to Diet.
The second action is FindRecord. However, instead of setting the Find What argu- ment to a fixed piece of text (="hay"), you point it to the SearchText control using the control name (=SearchText). If any spaces or special characters are in the control name, make sure you wrap the name in square brackets (=[SearchText]).
Tip: If you’re referring to a field or control on the current form, all you need to do is use the field or control name. However, sometimes you may want to refer to a control on another form. In this case, you need a wacky-looking syntax that indicates the form name and the control name. If you want to refer to a control named SearchText on a form named SearchForm, you’d write =Forms!SearchForm!SearchText.
Once you’ve polished off the macro, the last step is adding a button to the Ani- malTypes form to trigger it. Here’s how:
1. Select Form Tools | Design➝Controls➝Button, and then draw the button onto the form.
2. Press the Esc key to cancel the Button wizard.
3. In the Property Sheet, choose the Events tab.
4. Click the drop-down arrow next to the On Click event, and then, from the list, choose the macro you’ve just created.
5. Now choose the Format tab, and, in the Caption field, enter the word Search.
This descriptive text appears on the button.
This step completes the example. To try it out, switch to Form view, type something in the SearchText text box, and then click the Search button. You’ll skip ahead to the next matching record.
Changing Form Properties
Not only can you read form values, but you can also change them. The trick is a macro action called SetValue. SetValue is a remarkably powerful action, because it can change any property of a control. You can use it to change the text in a control, hide it, change its formatting, and so on. (For more about different control proper- ties you may want to use, see Chapter 13.) The only catch is that Access considers SetValue to be an unsafe action. You won’t see it unless you choose Macro Tools | Design➝Show/Hide➝Show All Actions, and Access won’t let you use it in an un- trusted database (page 489).
Conditional Macros
SetValue has only two arguments. The first argument, Item, identifies what you want to change. You can modify a form, section, field, or control. The second argument, Expression, sets the new value. You can use a fixed value, or you can read the value you want from another control using an expression.
If you want to create a macro that clears the search text from the SearchText text box, then you could add a SetValue action, and set the Item property to SearchText and the Expression property to " " (which represents a bit of text with nothing in it).
Note: This example assumes you’re using SetValue on the current form (for example, by clicking a button named Clear). If you’re running the macro from the navigation pane, you’ll need to change SearchText to the full name Forms!AnimalTypes!SearchText so it clearly tells Access which form you’re using.
If you like SetValue, then you may be interested in the related SetProperty action.
The SetProperty action changes one of a control’s properties. (You choose what property you want to change with the Property argument.) You can use SetProperty to change a control’s color, position, or captioning. However, the most common way to use SetProperty is to modify the Enabled property (to lock down controls that shouldn’t be editable) or the Visible property (to hide controls that aren’t relevant).
You can set both properties to True or False.
SetProperty’s nicest quality is that Access always considers it a safe action. The only drawback is that Access doesn’t let you set the Text property of a control, because then you could use it to modify a table.
Conditional Macros
The macros you’ve seen so far run all their actions from start to finish. If that seems a little boring, well, it is. But your macros don’t need to stay that way. You can let them make decisions and perform conditional actions.
To create a conditional macro, you need to use the If action. You can pick the If ac- tion from the Add New Action list (where it’s the third item), or you can drag it from the Program Flow section of the Action Catalog. Figure 16-4 shows an example.
Tip: To save some serious time, you can take a bundle of existing actions and wrap it with a new If box, with no dragging required. Simply press Shift as you select the actions you want to make conditional.
Then, right-click any part of this selection and choose Make If Block.
The If action requires a single argument, which is a condition. A condition is a little like an expression, except it always produces one of two results: True or False. Access
examines the condition and uses it to decide whether to run the actions inside the If box. (This is known as evaluating the condition in programmer-speak.) Here’s how it works:
• If the condition turns out to be True, Access runs the actions in the If box.
• If the condition turns out to be False, Access skips over the actions in the If box and continues with the next action after the If action.
Presto—you have a way to make an action run only when you need it.
Figure 16-4:
The If action is a bit like a group or a submacro, in that it holds one or more other actions. You add these actions by dragging them into the If box, or by using the Add New Action list that appears inside the If box.
Beginning of block Conditional actions go here End of bock
Building a Condition
This discussion raises one excellent question—namely, how do you build a condition?
The simplest types of conditions compare two different values. Here’s an example:
[ProductName] = "Baloney"
This condition compares the current value of the ProductName control with the word Baloney. If ProductName currently contains that text (and only that text), this condition is True. If ProductName contains anything else, the condition is False.
Tip: Sometimes you wind up with exactly the opposite of the condition you want. In a pinch, you can always reverse a condition by putting the word Not at the beginning. Not [ProductName]=”Baloney” is True only if the current item isn’t everyone’s favorite meat product.
The equal sign (=) is one of the staples of conditional logic, but it’s not your only op- tion. You can also use the greater than (>) and less than (<) symbols, and the “not equal to” (<>) operator. (You learned to use these operators with validation expressions on page 136.) Here’s an expression that checks if a numeric field is above a certain value:
[Price] > 49.99