Importing and Exporting Data

Một phần của tài liệu access 2010 the missing manual (Trang 493 - 525)

15 Automating Tasks

with Macros

The secret to a long and happy relationship with Access is learning how to make it work the way you want.

As you’ve already seen, true Access fanatics don’t use the ordinary datasheet to enter information. Instead, they create their own customized data entry forms.

Similarly, Access fans don’t print their data using basic yawn-inspiring tables. In- stead, they create richly formatted reports that are just right for presenting their data.

And Access pros definitely don’t struggle through the same tedious series of steps to accomplish a common task—instead, they create macros that make Access do the work for them.

A macro is a miniature program that you create and store in your database. Mac- ros can range from the exceedingly simple (like a command that shows a form) to the mind-bendingly complex (like a conditional macro that checks how much raw meat you have in stock, and automatically prints an order in triplicate if your fridge is empty).

In this chapter, you’ll learn how to create basic macros. Then, you’ll learn how to make them smarter. By the end of the next chapter, you’ll have completed your macro exploration, and you’ll be able to put together macros that can fire themselves up when needed, perform an entire sequence of steps, and even make decisions.

Automating Tasks with Macros

UP TO SPEED

Macros vs. Code

In the past, macros have had a bit of a mixed reputation.

Some Access gurus avoided them, preferring to use more powerful Visual Basic (VB) programming language (which you’ll pick up in Chapter 17). Microsoft contributed to the confusion by suggesting that macros were an old-school technique, and not the best option for forward-thinking developers.

These days, macros have a more respectable reputation.

Although macros don’t have anywhere near the power of raw VB code, they’re simple, clean, and convenient in a way that VB code can never be. They also have a couple of advantages.

One advantage that macros have over VB code is security.

Because Access knows what every macro does, it can vouch that most macros are safe. (For example, Access knows that an OpenForm macro action can be used only to open a form, so it doesn’t need to worry that it could delete your

files, spam your friends, or reformat your hard drive.) On the other hand, Access isn’t as trusting with VB code. As a result, it’s liable to lock out your code-powered features, even if they’re no more threatening than two bunnies cud- dling on a pillow. You’ll take a closer look at the security story on page 488.

Most macros also work with the web database feature you’ll explore in Chapter 23: You can take a macro-powered data- base, convert it to a web database, and still use its macros.

But if your database contains VB code, the VB-powered features can’t make the jump online.

Even if you’re planning to give macros a pass and become a black-belt Visual Basic coder, you should still start your Access programming career by learning about macros.

That’s because many of the concepts you’ll pick up—how macros plug into forms, how conditional logic works, and so on—also apply to VB code.

Figure 15-1:

This macro consists of two actions. The first action opens a table, and the second goes to a specific record. When you run the macro, Access starts at the top of the list and moves down, performing each action in sequence.

The first action

The second action

Macro Essentials

Although you may not realize it, you’ve already used macros. In Chapter 14, you cre- ated buttons that could perform useful tasks, like opening another form or navigating to a specific record. To create these actions, you used the Command Button wizard, which asks a few simple questions, and then generates a made-to-measure macro.

Although the Command Button wizard is easy to use, it’s not all that flexible. Now, you’re ready to get more power by building your own macros by hand.

Creating a Macro

In the following example, you’ll start slow, with a simple macro that opens a table, and then heads straight to the last row. Here’s how to create it:

1. Choose CreateMacros & CodeMacro.

A new window appears for you to create your macro. Unofficially, this window is known as the macro builder.

Every macro is made up of a sequence of one or more steps, or actions. To create a macro, you supply this list of actions, putting each one in a separate row (see Figure 15-1). Initially, this list is empty, and your macro doesn’t do anything at all.

2. Choose your first action in the Add New Action list.

Access has a predefined list of actions you can use to cook up a macro. When you add an action, you simply choose it from this list, as shown in Figure 15-2.

For this example, begin by choosing the OpenTable action.

Note: For the most part, the Add New Action list is alphabetical. However, Access makes an exception with a few special macro actions that it places right at the top of the list. They include Comment, for adding descriptive information (page 480); Group, for organizing sections of a macro (page 483); If, for creating conditional logic (page 512); and Submacro, for embedding several complete macros in a single macro object (page 500).

3. Fill in the arguments for your action, using the text boxes that appear under it (see Figure 15-3).

Most actions need some information from you in order to carry out their busi- ness. An OpenTable action doesn’t have much meaning unless you tell Access exactly what table you want it to open. These extra bits of information are called arguments.

Macro Essentials

Figure 15-2:

Click the drop-down arrow to see all the actions you can use. Right now, you’re working with only the actions that Access considers safe for all databases. A little later (on page 487) you’ll consider how you can use a few actions that Access considers risky business.

Figure 15-3:

When you select an action in the list, all the arguments ap- pear in text boxes under the action name. As this example shows, the OpenTable action has three arguments: Table Name, View, and Data Mode. You can type directly in a text box to set the argument value or, for some values, you can click the drop-down arrow at the right side of the text box to show a list of options. For example, if you click the drop- down arrow in the Table Name text box, you get a list of all the tables in your database.

The OpenTable action has three arguments:

Table Name is the table you want to open. You can choose it from a drop- down list of tables. For this example, you can use any table that isn’t empty.

View lets you pick the view mode that’s used. You can choose ordinary Datasheet view to enter information, Design view to change the table struc- ture, Print Preview to get ready to print the data, or PivotTable and Pivot- Chart to work with a pivot table summary (as described in Chapter 9). For

this example, choose Datasheet view. (Of course, once the table is open, you can still switch to a different view by right-clicking the tab title or by using the View button on the ribbon.)

Data Mode determines what type of changes are allowed. You can use the standard option, Edit, to allow all changes, Read Only to allow none, or Add to allow only record insertions. In this example, choose Read Only.

Note: You’ve already seen how custom macros have more power than the Command Builder wizard.

When using the Command Builder wizard, you can open forms and reports, but not ordinary tables, and you can’t control the view mode or the allowed types of edits. Macros don’t face these limitations.

4. Repeat steps 2 to 3 to add another action.

Every time you add an action, the Add New Action list moves down, so it sits right after the last action in your macro. To add a new action there, you simply pick a new action from the list.

You can add a practically unlimited number of actions to a macro. (For Access trivia buffs, macros top out at 999 actions.) When you run your macro, Access performs your actions in order, from top to bottom.

To complete this example, add a GoToRecord action. This action moves through the table you just opened to get to the record you want.

Using arguments, you’ll need to point out the correct object (set the Object Type to Table, and the Object Name to whatever table you picked in step 3).

Then, you can use the Record and Offset arguments to specify exactly where you want to end up. Using the Record argument, you can choose to head to the previous row (Previous), the next row (Next), the new row placeholder at the bottom of the table (New), a specific row (Go To), the first row (First), or—as in this example—the last row (Last). If you choose Go To, then you can use the Offset argument to point out a specific position—like setting it to 5 to jump to the fifth record.

Note: Some macro actions depend on previous macro actions. GoToRecord is a prime example—it assumes you opened a table, form, or query that has the record you want to see. If you use GoToRecord without having a suitable object open, you get an error message when you run the macro.

And just for fun, why not add one more macro action? Try the MessageBox action, which displays a message of your choosing in a small message window.

You set the message in the Message argument. Try something like “Your first macro just finished doing its job.” You can also add an optional title (using the Title argument), warning beep (by setting the Beep argument to Yes), and pre- defined icon (using the Type argument).

Macro Essentials

5. Press Ctrl+S to save your macro, and then provide a macro name.

You could name the macro in this example ShowTheLastProduct. If you don’t save the macro explicitly, then Access politely asks you to when you close the macro window, or when you run your macro for the first time.

Macros appear in the navigation pane. If you’re grouping objects by type, you’ll see that macros get their own type (named, rather predictably, Macros). If you’re using the “Tables and Related Views” grouping, Access adds macros to an extra group at the bottom named Unrelated Objects.

Note: When you use the Command Builder wizard, you’re also creating a macro. However, this macro doesn’t appear in the navigation pane, because it’s locked into a specific form. This type of macro is known as an embedded macro, because it’s embedded inside a form object. You’ll learn how to create embedded macros on page 509.

NOSTALGIA CORNER

New Names for Old Actions

If you’ve written macros for a previous version of Access, you’ll notice that a few of your favorite actions have new names in Access 2010. To make macro designing a little less intimidating, the designers of Access tinkered with some names. For example, they replaced MsgBox with the straightforward MessageBox and changed SendObject to the descriptive EMailDatabaseObject.

Fortunately, Access still recognizes the old names. Al- though you won’t see MsgBox or SendObject in the action list, if you type one of these names into the Add New Action box and press Enter, Access replaces it with the new name.

Running a Macro

Now that your macro is finished, you’re ready to try it out. Access gives you four ways to run a macro:

You can run it directly. Just find the macro you want in the navigation pane, and then double-click it. (This method works only if the macro isn’t already open.) Or, if the macro is open, choose Macro Tools | Design➝Tools➝Run.

Tip: If you’ve filtered the navigation pane (page 440) so that macros don’t appear, you can still run your macros. Just select Database Tools➝Macro➝Run Macro. You’ll then get the chance to pick your macro out of a list.

You can trigger it using a keystroke. You can, for instance, set up a macro that opens your end-of-month financial report whenever you press Ctrl+F. You’ll learn how on page 502.

You can run it automatically when the database is first opened. You could create a macro that always starts you out by running your favorite query and showing you the results. You’ll try this on page 504.

You can attach it to a form. You could set your macro to spring into action au- tomatically when a button is clicked or new data is entered. This way is the most common way to use macros, and the way the Command Builder wizard works.

You’ll explore this technique on page 506.

In this chapter, you’ll get a chance to try all these techniques. But right now, keep to the simplest option, and run the macro you created in the previous section by using the Macro Tools | Design➝Tools➝Run command. Figure 15-4 shows the result.

Figure 15-4:

Here’s the result of running the ShowTheLastProduct macro. Access opens the Products table (in Read-Only mode, so no changes are al- lowed), moves to the last, most recent re- cord, and then shows a message informing you that the macro is finished.

Editing a Macro

As you’ve just seen, building a simple macro is easy. You simply pick your actions one by one out of the Add New Action list. For each action, you fill in the related arguments using the handy text boxes.

Changing a macro is just as easy, and a few tricks can help you become a macro mas- ter. But before you can do anything, you need to open your macro in Design view. To do so, right-click it in the navigation pane and choose Design View. You arrive back at the macro window you used to create the macro in the first place.

Macro Essentials

Here’s what you can do to make changes to your macro:

Change action arguments. This part is easy. Just click to select an action, and all the text boxes appear again, so you can change as many values as you want.

Reorder actions. Click any part of an action (except inside a text box), and then drag the action to its new position. Access automatically bumps other actions out of the way. Alternatively, you can click it, and then use the up and down arrow keys on the keyboard. (And if you’re looking for yet another way to slide actions around, try using the green up and down arrow icons, which appear in the top-right corner of the action box when the action is selected.)

Add a new action. You already know about the Add New Action list, which sits at the bottom of every macro, waiting for you to choose another action. How- ever, there’s another way to find the action you want—using the Action Catalog, which sits at the right of the Access window. For more information, read the next section.

Remove an action. Select the action and press the Delete key. Or select the ac- tion and click the X icon in the top-right corner of the action box. Either way, make sure you really want to remove the action, because Access doesn’t ask you twice, and the Undo feature can’t bring it back. (If you do make a mistake, close your macro without saving it, and then open it anew.)

Add comments. Although a long, complex macro may make perfect sense to you, it might not be so clear to someone else who needs to change it (or to yourself, if you return to make changes many months later). To help keep things clear, good macro writers always add comments—simple text descriptions that Access ignores. To add a comment, choose the Comment action from the Add New Action list, which is the very first entry (Figure 15-5). Or, use this no-click shortcut: type // into the Add New Action box, followed by the text of your comment, and press Enter.

Tip: Don’t use comments to explain something that’s already obvious based on the action arguments. For example, “This opens the Orders table” isn’t a helpful description, because anyone looking at an Open- Table action can quickly figure out what table it opens. Instead, use comments to explain the significance of a step in a more complex operation. For example, “Opens the Orders table so you can delete expired orders” is better, because it fills in some details about what you’re trying to accomplish. Right now, you don’t need comments, but later on, when you create submacros and use conditions, you’ll see how they become useful.

Finding Actions in the Action Catalog

There’s nothing wrong with the Add New Action list. In fact, it’s a pretty convenient way to add new actions to a macro, if you already know what you want. But if you don’t know the name of the action you need, an alphabetical list isn’t a great help.

That’s where the Action Catalog comes in.

Figure 15-5:

This macro uses three comments to clarify how it works. Comments appear in green text and bracketed with the special charac- ter sequence /* at the beginning and */ at the end. This convention is bor- rowed from the program- ming world, which helps make macros look a little more like real code.

Comments

The Action Catalog is a pane on the right side of the macro designer, listing all of the possible actions you can use. (If you inadvertently close the Action Catalog, you can open it again by choosing Macro Tools | Design➝Show/Hide➝Action Catalog.) The difference between the Action Catalog and the Add New Action list is that the Action Catalog organizes actions into easy-to-understand groups (Figure 15-6).

For example, the Data Entry Operations group includes actions that delete and save records, and the Filter/Query/Search group includes actions that open queries, ap- ply filters, hunt for records, and trigger a refresh. To add an action from the Action Catalog, just find the right entry and drag it onto your macro. Unlike the Add New Action list, the Action Catalog doesn’t force you to place your new actions at the end of the macro. To save time, you can drop the new action between any existing actions.

The Action Catalog can also help out if you only roughly know the name of the ac- tion you want. At the top of the Action Catalog is a search box. Type a word from an action’s name, press Enter, and Access filters the Action Catalog so it shows only the actions that contain your search term. Access compares your search text to the action name and the action description. For example, typing import matches actions like ImportExportSpreadsheet, RunSavedImportExport, and Beep (because beep re- fers to “important visual changes” in its description).

Một phần của tài liệu access 2010 the missing manual (Trang 493 - 525)

Tải bản đầy đủ (PDF)

(832 trang)