Chapter 22. Writing Macros and Visual Basic Code in Outlook

IN THIS CHAPTER

  • Understanding macros

  • Using the Macros dialog box

  • Working with the VBA Editor

  • Security and macros

  • Assigning macros to menus and toolbars

  • Debugging macros

A macro is a sequence of program commands and keyboard input that has been saved. At any time, you can play the macro back and the result is exactly the same as if you had entered the same commands and input using the keyboard and mouse. Macros are terrific for automatic tasks that you perform regularly, and they can also help prevent errors.

Understanding Macros

Outlook (along with other Office programs) has a built-in programming language called Visual Basic for Applications, or VBA for short, that lets you write programs, called macros, to automate program operations. A macro may do something as simple as inserting a signature into an email message, or something as complex as sorting all incoming email into folders based on the sender. Macros offer two important benefits:

  • They save time. A sequence of actions that might take you a minute or more to perform manually can be executed essentially instantly with a macro.

  • They prevent errors. A properly written macro does not make mistakes. It performs the exact same sequence of commands each time it is run without typos or other errors.

You are not limited to using macros that you write. You may be able to get useful macros from your friends and colleagues, and some commercial products that add functionality to Outlook do so by means of macros. In any situation where you are considering a macro from an outside source, you must be aware of the issues surrounding macro security as discussed later in this chapter.

Many people use Outlook for years without ever wanting or needing to create or use macros. The fact is, however, that macros are an extremely powerful tool, and you may be missing a lot of time savings and error prevention if you ignore them.

The Macros Dialog Box

Outlook's macro command center is the Macros dialog box, shown in Figure 22.1. You open this dialog box by pressing Alt+F8 or selecting Macro from the Tools menu and then selecting Macros.

The Macros dialog box is Outlook's macro "command center."

Figure 22.1. The Macros dialog box is Outlook's macro "command center."

If you have any macros defined they will be listed here, otherwise the list will be empty. If you select an existing macro from the list, you can take the following actions by clicking the buttons in the dialog box:

  • Run: Execute the macro.

  • Step Into: Debug the macro. Debugging macros is covered later in this chapter.

  • Edit: Open the VBA editor to edit the macro.

  • Delete: Delete the macro.

To create a new macro, enter its name in the Macro Name box (the name must be unique for obvious reasons) and click the Create button. Outlook opens the VBA Editor with the shell—that is, the first and last lines—of the new macro in place, ready for you to add code.

The VBA Editor

The VBA Editor is where you create, edit, and debug macros. The editor is a powerful programming tool and is designed to make your programming efforts as easy as possible. You can open the editor from Outlook in several ways:

  • Press Alt+F11 (press Alt+F11 again to return to Outlook).

  • Select Macro from the Tools menu and then select Visual Basic Editor.

  • From the Macros dialog box, select the Edit or Create command (as explained in the previous section).

The VBA Editor is shown in Figure 22.2. You learn more about the editor's various tools and commands in subsequent chapters; for now it's enough for you to become familiar with the parts of the editor screen:

  • At the top left of the screen is the Project Explorer, where the editor lists the various components of the Outlook VBA project.

  • At the bottom left of the screen is the Properties window, where you view and edit the properties of whatever object is currently selected. In the figure, there is only a single property, but in other situations there will be dozens of properties listed here.

  • The main part of the screen, at the top right, displays one or more editing windows. It's here that you enter and edit VBA code.

  • At the bottom of the screen is the Immediate window, which you can use to debug macros.

The VBA Editor.

Figure 22.2. The VBA Editor.

Security and Macros

VBA is a powerful programming language. As such, it has the potential to do great harm to your data and files. So-called macro viruses have become more common, and are typically spread when Office documents are passed around as email attachments.

Outlook- based macro viruses are rarely if ever a problem because of the way its macros are stored. With other Office programs, such as Word and Excel, macros can be a part of an individual document and will go along with the document when it is forwarded as an attachment, thus permitting a malicious macro to be spread. In contrast, Outlook macros are not part of any document but are associated and stored with the Outlook program itself. In other words, you cannot pass an Outlook macro to someone else by sending them an email or any other Outlook data (you can specifically export an Outlook macro to send to someone else, but in that case it's obvious what's happening).

Does this mean that you need not be concerned with macro security? Absolutely not! Chapter 20 explains a variety of measures that Outlook users should take with regards to security.

Warning

Even when it comes to Outlook macros, you must use caution. Just because you cannot be infected with a malicious Outlook virus by means of an email attachment does not mean you are safe. If you plan to use macros from any outside source, you should use macros from trusted sources only, and when in doubt look over the macro source code to look for potential problems.

Assigning Macros to Menus and Toolbars

When you have a few macros that you use a lot, you may not want to open the Macros dialog box to run them each time. You can place a macro on a menu or a toolbar to make it more readily available. The procedures are similar to those for customizing menus and toolbars that were covered in Chapter 19. You may want to create a new toolbar, as explained in that chapter, specifically for macro commands:

  1. In Outlook, select Customize from the Tools menu to display the Customize dialog box.

  2. If necessary, click the Commands tab.

  3. Select Macros in the Categories list. As shown in Figure 22.3, the Commands list displays the names of all macros.

  4. To place a macro on a toolbar or menu, drag it from the list and drop it at the desired position on the toolbar or menu.

  5. When finished placing commands, click Close to close the Customize dialog box.

Assigning macros to menus and toolbars.

Figure 22.3. Assigning macros to menus and toolbars.

By default, a macro is displayed on a menu or toolbar with the macro name and the generic Macro icon, as shown in Figure 22.4.

A toolbar or menu initially displays a macro's name and a default icon.

Figure 22.4. A toolbar or menu initially displays a macro's name and a default icon.

You can change how a macro is displayed on a toolbar or menu. First, you have to open the Customize dialog box by selecting Customize from the Tools menu. You do not actually use the dialog box in these procedures, but it must be open for the menus and toolbars to be in edit mode. Then, right-click the macro item on the menu or toolbar to display the context menu shown in Figure 22.5. The commands are

  • Reset: Resets the button to the default appearance.

  • Delete: Deletes the button from the toolbar or menu.

  • Name: In the adjacent box, edit the text that is displayed on the button.

  • Copy Button Image: Copy the button's image so you can paste it into another button.

  • Paste Button Image: Use the image copied from another button.

  • Reset Button Image: Resets the button to the default "macro" icon.

  • Edit Button Image: Opens an icon or button editor, shown in Figure 22.6, where you can edit the button's image.

  • Change Button Image: Lets you select from a gallery of button designs, as shown in Figure 22.7.

  • Default Style: Sets the button to display an icon only (no text).

  • Text Only (Always): Sets the button to display text only both in toolbars and on menus.

  • Text Only (in Menus): Sets the button to display text only on menus.

  • Image and Text: Sets the button to display both text and an image.

  • Begin a Group: Adds a vertical (on toolbars) or horizontal (on menus) divider before the button.

  • Assign Hyperlink: Lets you assign a hyperlink to a toolbar item.

This context menu provides commands for changing how macros are displayed on toolbars and menus.

Figure 22.5. This context menu provides commands for changing how macros are displayed on toolbars and menus.

The Button Editor lets you customize the appearance of toolbar buttons.

Figure 22.6. The Button Editor lets you customize the appearance of toolbar buttons.

Selecting a button design from the button gallery.

Figure 22.7. Selecting a button design from the button gallery.

Debugging Macros

When you create a macro, you may find that it does not do exactly what you wanted it to do. This is called a bug and the Outlook VBA Editor provides you with some tools for finding and fixing bugs. Generally, bugs are almost always the result of one or both of the following problems:

  • A program variable takes on the wrong value.

  • Program execution takes the wrong path through the macro code.

The debugging tools let you address both of these problems as follows:

  • Breakpoints let you temporarily suspend the macro's execution at specified lines of code or when specified conditions are met.

  • Watches let you examine and change the value of variables during macro execution.

  • Controlling execution lets you execute a program one line at a time and control the path execution takes.

Working with Breakpoints

When a macro is executing inside the VBA Editor, you can temporarily pause macro execution—in other words, put the macro in break mode. You do this by setting one or more breakpoints, which specify that the program should pause either when a specified line of code is reached or when a certain condition is met. When a program is in break mode, the next statement to be executed is highlighted in the editor window (if possible—the next statement may not be known), and you can carry out various actions to help track down the cause of a bug. Then, you can continue execution normally or terminate the program.

When in break mode, you can rest the mouse pointer over a variable name in your code and the VBA Editor will display the current value of the variable in a small window. You can also edit your code, with some limitations. The other tools described in this section are also available in break mode.

To enter break mode when execution reaches a certain location in your macro code, set a breakpoint on that line. Before you start execution, or while in break mode, move the editing cursor to the line and press F9. A line that has a breakpoint set is displayed in a different color and with a dot in the left margin, as shown in Figure 22.8. Execution pauses just before executing the line with the breakpoint. You can set breakpoints on as many lines as you want. Press F9 again to remove the breakpoint from a line. Press Ctrl+Shift+F9 to remove all breakpoints.

A breakpoint displays as shown in the VBA Editor.

Figure 22.8. A breakpoint displays as shown in the VBA Editor.

You can also enter break mode based on the value of variables in your program. For example, you could specify that the program enters break mode when the variable Count has the value 100. You learn about this technique in the next section, "Using Watches."

When you are finished working in break mode, press F5 to continue macro execution. Other options for controlling program execution are covered in the section "Controlling Program Execution" later in this chapter.

Using Watches

While you are debugging a macro you can use watch expressions to keep track of the data your macro is working with. A watch can be any expression—variables, properties, functions, and so on. Because many program bugs are caused by variables and properties taking on unexpected values, the use of watches is an important debugging tool.

VBA supports two types of watches and you can choose the one that's right for your needs. Regular watches are displayed in the Watches window, which you open by selecting Watch Window from the View menu. You can have multiple watch expressions in the window, and VBA displays the following for each one:

  • Value: The current value of the watch expression.

  • Type: The data type of the watch expression.

  • Context: The names of the module and macro where execution is paused.

The Watches window is shown in Figure 22.9. It indicates the variable Count is type Integer and has the value 45, and the variable temp is type String as has the value "Week of 12/12/2006".

Use the Watches window to view the value of variables and expressions during macro debugging.

Figure 22.9. Use the Watches window to view the value of variables and expressions during macro debugging.

A watch expression can be a single variable or an expression made up of variables and any of VBA's operators and functions. You would create watch expressions when you are interested in the relationship between variables rather than their exact values. For instance, you might need to keep track of whether the variable Count is greater than the variable Max without regard to their actual values. The watch expression Count >Max displays a result of either True or False depending on the data. Likewise, if you want to see whether a string's length is less than 10, you would use the watch expression Len (SomeString) <10.

To add a variable to the Watches window, right-click the variable name in your code and select Add Watch from the popup menu. To add an expression to the Watches window:

  1. Move the editing cursor to any location in the code you are debugging.

  2. Select Add Watch from the Debug menu. VBA displays the Add Watch dialog box (see Figure 22.10).

  3. Enter the desired watch expression in the Expression box.

  4. Make sure the Watch Expression option is selected.

  5. Click OK.

Each time the program enters break mode the display in the Watches window is updated. Then, you can examine the values of your watch expressions to determine whether they reveal anything about the bug you are working on. You can also edit a watch expression, or delete it from the window, by right-clicking it and selecting from the popup menu.

Adding a watch expression to the Watches window.

Figure 22.10. Adding a watch expression to the Watches window.

The second type of watch is called a Quick Watch. When the macro is in break mode, highlight an expression in your code and select Quick Watch from the Debug menu (or press Shift+F9). VBA displays a box containing the current value of the expression as well as its data type and context. Figure 21.11 shows a Quick Watch display.

Watches can also be used to control break mode. For example, you can specify that the macro break either when a watch expression is True or when a watch expression changes value. You add this type of watch using the Add Watch dialog box (see Figure 22.10), and is displayed in the Watches window along with other watches. Type the expression in the Expression box of the Add Watch dialog box, then select either the Break When Value Is True or Break When Value Changes option. In the Watches window, the three types of watches—regular, break on true, and break when changes—are displayed with different symbols in the left column. When a program breaks based on a watch expression, the corresponding watch expression is highlighted in the Watches window.

Displaying Quick Watch information about an expression.

Figure 22.11. Displaying Quick Watch information about an expression.

The Locals Window

VBA provides yet another useful way of keeping track of the values of program variables—the Locals window. To display this window, shown in Figure 22.12, select Locals Window from the View menu. You cannot specify what is shown in this window—it always displays the values and types of all variables, properties, objects, and constants that are in scope at the time the program enters break mode.

The Locals window.

Figure 22.12. The Locals window.

Controlling Macro Execution

The ability to control the execution of your macro can be an essential part of debugging. Earlier in this section you have seen how to pause macro execution, entering break mode based on code location or on the value of program variables. Once you are finished working in break mode, you have several choices on the Debug menu:

  • Continue (F5): Continues macro execution normally.

  • Step Into (F8): Executes the next statement then pauses in break mode. If the next statement is a procedure call, pauses at the first statement in the procedure.

  • Step Over (Shift+F8): Executes the next statement then pauses in break mode. If the next statement is a procedure call, executes the entire procedure then pauses after exiting the procedure. This command has the same effect as Step Into if the next statement is not a procedure call.

  • Step Out (Ctrl+Shift+F8): Executes to the end of the current procedure, then pauses in break mode.

  • Run to Cursor (Ctrl+F8): Executes to the line of code containing the cursor, then pauses in break mode.

The Step Into and Run to Cursor commands are available even when you are not in break mode. By using one of these commands to start the macro, rather than the usual Run Sub/User Form command (or pressing F5), you can start the project and run it one line at a time, or up to the cursor.

What's Next?

This chapter has just scratched the surface of Outlook macros and VBA programming. Here's a brief look at what's coming up. The next three chapters deal with macros and VBA programming in more detail:

  • Chapter 23 deals with the VBA language and how it is used to write macros. You need an understanding of VBA structure and syntax before you can proceed.

  • Chapter 24 explores the Outlook Object Model, which provides the VBA programmer with a rich set of objects that represent various elements in Outlook, such as messages, contacts, and tasks. Macro programming is mostly a matter of manipulating these objects to accomplish your task.

  • Chapter 25 walks you through some complete, real-world examples of Outlook macros.

Summary

This chapter has introduced you to Outlook macros and VBA programming. Macros let you automate repetitive, commonly performed tasks and can save you time and errors. Though you cannot record macros in Outlook, you can create your own and import macros from friends and colleagues. There's a lot more to learn, so stay tuned.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.18.253