Professional Documents
Culture Documents
MBAs GUIDE to
The Essential Excel Reference for Business Professionals
MBAs Guide to Microsoft Excel 2002: The Essential Excel Reference for Business Professionals
Copyright 2001 Stephen L. Nelson and David B. Maquiness All rights reserved. No part of this book may be reproduced in any form or by any method or any means without the prior written permission of the publisher. Published by Redmond Technology Press 8581 154 th Avenue NE Redmond, WA 98052 www.redtechpress.com Library of Congress Catalog Card No: Applied for ISBN 1-931150-01-X Printed and bound in the United States of America. 987654321
Distributed by Independent Publishers Group 814 N. Franklin St. Chicago, IL 60610 www.ipgbook.com
Product and company names mentioned herein may be the trademarks of their respective owners.
In the preparation of this book, both the author and the publisher have made every effort to provide current, correct, and comprehensible information. Nevertheless, inadvertent errors can occur and software and the principles and regulations concerning business often change. Furthermore, the application and impact of principles, rules, and laws can vary widely from case to case because of the unique facts involved. For these reasons, the author and publisher specifically disclaim any liability or loss that is incurred as a consequence of the use and application, directly or indirectly, of any information presented in this book. If legal or other expert assistance is needed, the services of a professional should be sought.
USING MACROS
Featuring:
Understanding VBA Creating Macros Running Macros Editing Macros Sharing Macros Macro Examples his chapter introduces you to Excel macros by showing you how to create simple macros using Excels Macro Recorder and how to run them. Youll also get acquainted with Microsoft Visual Basic for Applications (VBA), the language that is used by Excel for macros. Finally, several macros are presented to help you with common worksheet tasks.
NOTE
Although this chapter describes the basics of creating and running Excel macros, youll find that the process of creating and running macros in other Office applications is very similar.
Understanding VBA
All Office applications rely on VBA for their macro language. VBA is a version of the Visual Basic programming language designed specifically for Office applications. Visual Basic itself is descended from the BASIC programming language. You can create simple macros using the Macro Recorder, which records your actions and allows you to play them back later. More complex macros require that you use the Visual Basic Editor to create them. Similar to the Macro Recorder, the Visual Basic Editor is available from any Office application, as displayed in Figure A-1.
Figure A-1
The Visual Basic Editor contains a title bar, a menu bar, and toolbars similar to Office applications. The Visual Basic Editor also contains the following three windows: Project Explorer window Properties window Code window
The Project Explorer window displays the projects that are currently open in the application. Projects consist of the VBA code and forms, if any, you created, and objects of the application. In Excel, a project consists of VBA code, any forms, and Excel objects, such as worksheets and charts. Note that a workbook always has a project even if you have not created a macro. You navigate the Project Explorer window in a way similar to that of the left pane of Windows Explorer. The Properties window displays information about the currently selected item in the Project Explorer window. For example, if you have a worksheet selected in the Project Explorer window, attributes about the worksheet are displayed in the Properties window, such as whether the worksheet has been saved. Depending on the property, you can change the propertys value. The Code window displays the macro code contained in the modules of all open workbooks. To display the code, open a Module folder in the Project Explorer pane and select a module. Its associated code is displayed in the Code window. If you have a programming background or are familiar with Visual Basic, youll feel right at home with VBA. If you are new to programming and your macro needs go beyond those created by using the Macro Recorder, you may want to consider learning how to program and then apply those skills to the VBA language. One effective way to learn how to program is to take a beginning course at a local college. In this manner, you learn good programming techniques. Another way is to learn one-on-one from a programmer who is willing to work with you on developing your programming skills. Whether you are an experienced programmer or a newcomer who wants to learn more about VBA, you can view and print the online programmers reference to VBA at the following address: http://msdn.microsoft.com/library/default.asp?URL=/library/officedev/odeopg/ deovroffice2000visualbasicprogrammersguide.htm.
Creating Macros
You can create macros by using the following methods: Using the Macro Recorder Copying the macro from another workbook Typing the macro directly Lets look at each of these alternatives.
Using Macros
5
If you prefer using toolbar tools rather than menu commands, click View, click Toolbars, and then click Visual Basic. You can perform many of the actions in the following sections using the Visual Basic toolbar.
To create a macro using the Macro Recorder, follow these steps: 1. Display the worksheet where you want to record your actions. 2. Open the Record Macro dialog box, as shown in Figure A-2. Click the Tools menu, click Macro, and then click Record New Macro.
Figure A-2
3. Name the macro. Type a name in the Macro Name box. Use a name that describes the purpose of the macro and that will be easy to remember.
4. If you want the option of using a shortcut key to run the macro, type a letter in the Shortcut key box. Each time you press a Ctrl key and the shortcut key, the macro will run. If you use Shift and a letter to enter your shortcut key, you use Ctrl+Shift and the shortcut key to run the macro. 5. From the Store Macro In list, select where you want the macro stored. You have three options: Personal Macro Workbook, This Workbook, or New Workbook. Select Personal Macro Workbook if you want to use the macro with any workbook. (The macros in the Personal Macro Workbook are always available.) Select This Workbook to store the macro in the active workbook because you want to use the macro with that workbook. Select New Workbook to direct Excel to open a new workbook to store the macropresumably the workbook where youll use the macro. 6. Optionally, describe the macro in more detail. If you want to include information about the macro, type it in the Description box, or accept the default information. If you do not want to include a description, select and delete the default information. Macro descriptions appear in the Macro dialog box as well as in the Visual Basic Editor. Omitting a description results in less cluttered code in the Visual Basic Editor, but a description can provide important documentation about your macros. 7. Click OK. Recording appears next to Ready on the Status Bar, and the Stop Recording toolbar appears. If the Visual Basic toolbar is displayed, the Stop Recording tool is highlighted. 8. Type the keystrokes you want to record. To follow along with the example were discussing here, type the information shown in Figure A-3. If you were creating your own macro, of course, you would type the actual keystrokes you wanted to record.
Using Macros
Figure A-3
9. Tell the Macro Recorder to stop recording. From the Stop Recording toolbar or Visual Basic toolbar, click Stop Recording so that the Macro Recorder stops recording. You can run your macro from the Macro dialog box or by using a shortcut key if you assigned one.
You can also display the Visual Basic Editor by clicking the Visual Basic Editor tool on the Visual Basic toolbar or by pressing Alt-F11.
Figure A-4
2. Select the VBA project. From the Project window, select the name of the VBA project that represents the workbook that contains the macro. 3. Select the macro, as shown in Figure A-5. From the Module1 folder, double-click the module that contains the macro. The macro appears in the Code window.
Using Macros
Figure A-5
The macro as it appears in the Code window of the Visual Basic Editor.
10
Figure A-6
2. Name the macro. In the Macro Name box, type a name for the macro. 3. Optionally, provide a shortcut for the macro. If you want the option of using a shortcut key to run the macro, type a letter in the Shortcut Key box. 4. Indicate where to store the macro. From the Store Macro In list, select where you want the macro stored. 5. Optionally, describe the macro. If you want to include information about the macro, type it in the Description box or accept the default information. If you do not want to include a description, select and delete the default information. 6. Begin recording. To begin recording your keystrokes, click OK. 7. Tell Excel to assume relative cell references. From the Stop Recording toolbar, click the Relative Reference tool. Note that Excel doesnt record clicks and keystrokes you may using the Stop Recording toolbar. 8. Type the keystrokes you want to record. Once you tell Excel to assume relative cell references, type the keystrokes you want to record. To follow along with the example described here, type the information as shown in Figure A-7.
Using Macros
11
Figure A-7
9. Tell the Macro Recorder to stop recording. From the Stop Recording toolbar or Visual Basic toolbar, click Stop Recording so that the Macro Recorder stops recording. Figure A-8 displays the macro recorded with relative cell references (Macro2).
12
Figure A-8
NOTE
Each macro uses the same number of lines of code, but Macro1 uses ActiveCell.FormulaR1C1 while Macro2 uses ActiveCell.Offset. If you need labels in the same range every time, use Macro1; otherwise, use Macro2 for greater flexibility.
Using Macros
13
Use one of the Tile commands or the Cascade command from the Visual Basic Editors Window menu to arrange the Code windows to help you quickly copy and paste macro code.
Running Macros
To run macros, you can use the following options: Excels Tools menu A shortcut key combination A toolbar tool An object on a worksheet Automatically each time you open a workbook The method you choose depends on the purpose of the macro and your personal preference, or what is appropriate for your audience if you are developing a macro for others use. Keep in mind that you are not limited to one method but rather you can use any combination of options from those listed above, depending on how you created the macro initially. For example, you can run macros from the Tools menu, by using a shortcut key combination, and by clicking a toolbar tool. The following sections help you decide which methods are best for your situation.
14
Figure A-9
2. Select the macro you want to run. Click the macro name to select it in the Macro Name list. 3. Click Run. The Macro dialog box closes, and the selected macro runs.
TIP
Click the Run tool on the Visual Basic toolbar to quickly display the Macro dialog box.
Using Macros
15
Keep a list of the names of your macros and their corresponding shortcut keys in a separate worksheet in the workbook.
16
4. Indicate you want to add a toolbar command. Click the Commands tab, and select Macros from the Categories list. Then click the Custom button. 5. Add a tool to the toolbar. To add a tool, click it to select it and then drag it to the toolbar. 6. Assign the macro to the tool. Right-click the tool, and choose Assign Macro from the shortcut menu, as shown in Figure A-11.
Using Macros
17
When Excel displays the Assign Macro dialog box, as shown in Figure A-12, select the macro and click OK. The macro is assigned to the toolbar tool.
Once youve assigned the macro to a toolbar tool, you can run the macro by clicking the toolbar tool.
TIP
The tool shortcut menu enables you to select another image or create your own by using the Change Button Image and Edit Button Image commands, respectively.
4. Open the Assign Macro dialog box, as shown in Figure A-14. Click Assign Macro on the shortcut menu.
5. Select the macro you want to run. Click the macro to select it in the Macro Name list. 6. Click OK. The macro is assigned to the object. The mouse pointer appears as a pointing finger when the pointer passes over the object. Clicking once runs your macro. If you need to assign a different macro to the object, repeat steps 3 through 6.
Editing Macros
You can edit the macros you or someone else has created. To do so, you use the Visual Basic Editor. You begin editing a macro by displaying it in the Code window. To display a macro, click the Tools menu, click Macro, and then click Macros. When Excel displays the Macros dialog box, select the macro you want to edit from the Macro Name list. Then click Edit. The macro appears in the Code window.
20
TIP
You can display a macro if it is assigned to a worksheet object by right-clicking the object, choosing Assign Macro from the shortcut menu, selecting the name of the macro, and clicking Edit. You can also display macro code directly from the Visual Basic Editor by selecting the name of a module from the Project Explorer window.
You edit the code in the same way that you would in any Windows text or word-processing program. You select, delete, or add code by using the keyboard, mouse, and pasting from the Clipboard. For example, if you accepted the information in the Description box of the Record Macro dialog box, you can delete it from your macro by selecting this information in the Code window and then pressing the Delete key.
Sharing Macros
You can share macros that you or others have created. You can use the macros created by another user by making a copy of his or her PERSONAL.XLS workbook and using it as your own workbook. You can also open a copy of the workbook that contains macros that you want to use and copy one or more. Then you activate the workbook in which you want to store the macros. You paste the copied macro into a new or existing macro in the Code window.
Macro Examples
The macro examples in this section can easily be created using the Macro Recorder. They are presented here to demonstrate the Macro Recorders capability and to give you a feel for an Excel task and its VBA equivalent.
NOTE
Make sure you include Sub and End Sub if you copy any of these macros for your workbooks.
Using Macros
21
Erase only the formatting of a selected range. Sub Macro2() Selection.ClearFormats End Sub
Format a range with the currency symbol and comma. Sub Macro3() Selection.NumberFormat = $#,##0.00 End Sub
Paste values. Sub Macro6() Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _ False, Transpose:=False End Sub
22
Paste values. Sub Macro7() With ActiveSheet.PageSetup .PrintTitleRows = .PrintTitleColumns = End With ActiveSheet.PageSetup.PrintArea = With ActiveSheet.PageSetup .LeftHeader = .CenterHeader = .RightHeader = .LeftFooter = .CenterFooter = .RightFooter = .LeftMargin = Application.InchesToPoints(0.75) .RightMargin = Application.InchesToPoints(0.75) .TopMargin = Application.InchesToPoints(1) .BottomMargin = Application.InchesToPoints(1) .HeaderMargin = Application.InchesToPoints(0.5) .FooterMargin = Application.InchesToPoints(0.5) .PrintHeadings = False .PrintGridlines = True .PrintComments = xlPrintNoComments .PrintQuality = 600 .CenterHorizontally = False .CenterVertically = False
Using Macros
23
.Orientation = xlPortrait .Draft = False .PaperSize = xlPaperLetter .FirstPageNumber = xlAutomatic .Order = xlDownThenOver .BlackAndWhite = False .Zoom = 100 End With End Sub
Summary
New and casual Office users sometimes fear macros, but thats too bad. As this chapter shows, macros dont have to be that difficult to understand, create, or use. Simple macros can easily be created using the Macro Recorder. So anytime you have a repetitive, multiple-step task that you perform in Excel or one of the other Office programs, consider writing and then using a macro.
24