Macros Excel Vba
Macros Excel Vba
Copyright 2008 by Key Training Solutions Ltd. All rights reserved. Information in this document is subject to change without notice and does not represent a commitment on the part of Key Training Solutions Ltd. Trademarked names appear throughout this book. Rather than list the names and entities that own the trademarks or insert a trademark symbol with each mention of the trademark name, Key Training Solutions Ltd states that it is using the names for editorial purposes and to the benefit of the trademark owner with no intention of infringing upon the trademark.
DISCLAIMER
Key Training Solutions Ltd has taken every effort to ensure the accuracy of this manual. If you should discover any discrepancies, please notify us immediately.
IMPORTANT NOTE
Unless otherwise stated, screenshots of dialog boxes and screens in this lesson were taken using Excel 2003 running on Window XP Professional. There may, therefore, be minor cosmetic differences if you are using Excel 2000 or 2002(XP), or if you are running on Windows 2000 or Windows Vista. Concepts, discussions, procedures and functionality, however, remain unchanged.
Page 2
Contents
ABOUT KEY TRAINING SOLUTIONS LTD .................................................................................................. 2 COPYRIGHT & TRADEMARKS...................................................................................................................... 2 DISCLAIMER ...................................................................................................................................................... 2 IMPORTANT NOTE ........................................................................................................................................... 2 LESSON 1 - RECORDING MACROS .............................................................................................................. 5 WORKING WITH VISUAL BASIC FOR APPLICATIONS ........................................................................................... 6 DEFINING MACROS ............................................................................................................................................. 6 RECORDING A MACRO ........................................................................................................................................ 6 RUNNING A MACRO .......................................................................................................................................... 10 RECORDING A MACRO USING RELATIVE REFERENCES..................................................................................... 11 SAVING A WORKBOOK CONTAINING A MACRO ................................................................................................ 12 OPENING A WORKBOOK CONTAINING A MACRO .............................................................................................. 13 SAVING THE PERSONAL MACRO WORKBOOK ................................................................................................... 17 Exercise........................................................................................................................................................ 18
Recording Macros ..................................................................................................................................................... 18
LESSON 2 THE VISUAL BASIC EDITOR ................................................................................................ 20 LAUNCHING THE VISUAL BASIC EDITOR .......................................................................................................... 21 NAVIGATING THE VISUAL BASIC EDITOR ......................................................................................................... 22 FINDING A MACRO IN THE VISUAL BASIC EDITOR ............................................................................................ 22 INSERTING A MODULE INTO A WORKBOOK ....................................................................................................... 24 COPYING A MODULE BETWEEN WORKBOOKS .................................................................................................. 25 RENAMING A MODULE SHEET ........................................................................................................................... 26 DELETING A MODULE SHEET ............................................................................................................................ 27 Exercise........................................................................................................................................................ 28
Using the VB Editor .................................................................................................................................................. 28
LESSON 3 - ASSIGNING MACROS .............................................................................................................. 29 ASSIGNING A SHORTCUT KEY ........................................................................................................................... 30 ADDING A CUSTOM TOOLBAR BUTTON (EXCEL 2000 - 03 ONLY) ..................................................................... 31 ADDING A MACRO BUTTON TO THE QUICK ACCESS TOOLBAR (EXCEL 2007 ONLY)........................................ 32 CREATING A NEW TOOLBAR (EXCEL 2000 - 03 ONLY) ...................................................................................... 33 ASSIGNING A MACRO TO A MENU (EXCEL 2000 - 03 ONLY) ............................................................................. 34 CREATING A NEW MENU (EXCEL 2000 - 03 ONLY) ........................................................................................... 35 DELETING A CUSTOM TOOLBAR BUTTON OR CUSTOM MENU ITEM (EXCEL 2000 - 03 ONLY) .......................... 36 USING A MACRO BUTTON ................................................................................................................................. 37 CREATING A MACRO BUTTON........................................................................................................................... 37 COPYING A WORKSHEET MACRO BUTTON ....................................................................................................... 39 EDITING A WORKSHEET MACRO BUTTON ......................................................................................................... 40 DELETING A MACRO BUTTON ........................................................................................................................... 42 Exercise........................................................................................................................................................ 43
Assigning Macros...................................................................................................................................................... 43
LESSON 4 WRITING PROCEDURES ....................................................................................................... 45 INTRODUCTION TO EXCEL OBJECTS.................................................................................................................. 46 METHODS AND PROPERTIES .............................................................................................................................. 49 RETURNING METHODS AND PROPERTIES .......................................................................................................... 52 ADDING ARGUMENTS TO METHODS ................................................................................................................. 53 PROPERTIES THAT ARE ALSO OBJECTS............................................................................................................. 55 SELECTION OR ACTIVECELL? ........................................................................................................................... 56 WRITING VBA SUB PROCEDURES ..................................................................................................................... 58 THE WITH ... END WITH BLOCK........................................................................................................................ 62 THE OFFSET FUNCTION ..................................................................................................................................... 63
Contents
DEALING WITH A RUNTIME ERROR ................................................................................................................... 65 USING THE OBJECT BROWSER ........................................................................................................................... 67 Exercise........................................................................................................................................................ 69
Writing Sub Procedures............................................................................................................................................. 69
LESSON 5 - CONTROL STRUCTURES ....................................................................................................... 72 THE IF-THEN CONTROL STRUCTURE ................................................................................................................. 73 THE IF-THEN-ELSE CONTROL STRUCTURE ....................................................................................................... 76 USING ELSEIF IN A CONTROL STRUCTURE ........................................................................................................ 77 THE SELECT CASE CONTROL STRUCTURE......................................................................................................... 79 USING A DO LOOP STATEMENT......................................................................................................................... 81 Exercise........................................................................................................................................................ 85
Decisions-Making Code and Do Loops ..................................................................................................................... 85
LESSON 6 DATA VARIABLES ................................................................................................................... 86 DATA VARIABLES ............................................................................................................................................. 87 CREATING VARIABLES AND ASSIGNING VALUES .............................................................................................. 87 VARIABLE TYPES .............................................................................................................................................. 91 Exercise........................................................................................................................................................ 94
To Assign Values To Variables. ................................................................................................................................ 94
LESSON 7 - USING THE FOR LOOP ....................................................................................................... 95 USING A FOR... NEXT LOOP .............................................................................................................................. 96 USING A FOR EACH... NEXT LOOP..................................................................................................................... 99 Exercise...................................................................................................................................................... 105
Create a For Loop Structure. ................................................................................................................................... 105
LESSON 8 - ADDING INTERACTIVITY TO MACROS .......................................................................... 106 THE MSGBOX FUNCTION................................................................................................................................. 107 CREATING AN INTERACTIVE MESSAGE BOX ................................................................................................... 108 CREATING A CUSTOM INPUT BOX ................................................................................................................... 113 Exercise...................................................................................................................................................... 117
Using Interactivity ................................................................................................................................................... 117
APPENDIX I - MACRO SECURITY ............................................................................................................. 118 SECURITY LEVELS........................................................................................................................................... 119 CHANGING MACRO SECURITY SETTINGS ........................................................................................................ 121 TRUSTED LOCATIONS (EXCEL 2007) ............................................................................................................... 122 INDEX ............................................................................................................................................................... 124 HELP SERVICE .............................................................................................................................................. 126
Page 4
DEFINING MACROS
Discussion
A macro is a small program that you can use to perform frequently used simple operations automatically, or for more complex tasks that require consistency. It contains all the commands and actions necessary to complete a task. Excel macros are written in the VBA programming language. The series of commands used in a macro are known as a procedure. Each procedure is given a name that is used to identify the macro for later execution (running) and editing. Each procedure is saved in a device called a module. In Excel, this module is attached to the worksheet in which the macro was written. Since Office 97, a module cannot be seen in the normal Excel window because it is hidden. You must use the Visual Basic Editor to select a module and view, write or edit the macro code. In order for a macro to run, the Excel file containing the VBA code must be open.
RECORDING A MACRO
Discussion
A macro can be created using the macro recorder. You perform the steps you want to include in the macro and Excel records them into a macro procedure. The steps you perform are translated into VBA, which uses macro statements to replace your steps.
Page 6
When you record a macro, Excel creates a module that is attached to a worksheet. A module can contain more than one macro. At the start of the macro recording process, you enter the following information into the Record Macro dialog box: Macro name: Type a name for the macro. The macro name can contain letter, numbers and underscores but MUST begin with a letter. The name cannot contain spaces or punctuation marks There is a limit of 64 characters to a macro name. Shortcut key: Type a letter that you wish to use in conjunction with the CTRL key to run the macro later. For example, if you press x you can later run the macro using CTRL x. Tip: Most of the CTRL <something> keystrokes are already used by Excel for other commands (eg. CTRL o for File Open, CTRL c for Copy). To avoid the macro keystroke overriding the standard Excel command, combine the SHIFT key with the keystroke. For example, by entering SHIFT O into the Shortcut key: box, the macro will run using CTRL SHIFT O, thus avoiding normal Excel keystrokes. Store macro in: Select the location where you want the macro recorder to store the VBA code for the macro. The code can be stored in the Personal Macro Workbook, a New Workbook or This Workbook. The Personal Macro Workbook is a special Excel file that Excel creates for you the first time that you record a macro in it. Excel names this file personal.xls and stores it in a folder named XLSTART. The XLSTART folder forms part of your personal settings (profile) so should always be available at any computer that you log on to and which is connected to your corporate network. Excel manages personal.xls by automatically saving it when you exit Excel, and automatically opening it when you launch Excel. As a result, any macros in the Personal Macro Workbook should always available for you to use. The Personal Macro Workbook is the ideal place, therefore, to store general purpose macros that you may want to use on ANY Excel file. Recording a macro in This Workbook is more usual in cases where the macro is specific to that workbook only. For example, a macro that carries out an analysis explicit to a table that is found in that workbook only. Storing a macro in This Workbook also makes it more available and transportable in shared situations. For example, if you send the workbook as an attachment, the macro will also be available to the recipient. If you had stored the same macro in the
Key Training Solutions Limited Page 7
personal macro workbook, it would be available to you only. Recording a macro in a New Workbook is the same as This Workbook; the difference being that Excel will create a new file to store the macro in rather than storing it in the active file that you are recording the macro from. Description: Type a comment or note(s) about the macro in general. For example, instructions on how to run the macro, an explanation what the macro is designed to do, etc.
Studying the Visual Basic code generated by the recorder is an excellent way of getting acquainted with the VBA language.
Page 8
9. Perform the actions that you wish the macro to repeat later. 10. Click the Stop button when finished.
NB If you do not see the Stop Recording toolbar, you can stop the macro by clicking Tools - Macro - Stop Recording. Excel 2000 - 03 only Commands for working with macros can be accessed more quickly by displaying the Visual Basic toolbar (View - Toolbars - Visual Basic)
9. Perform the actions that you wish the macro to repeat later. 10. Click the Stop button in the status bar when finished, or - Click the View tab on the Ribbon. - Click the Macros button in the Macro group. - Select Stop Recording.
Page 9
RUNNING A MACRO
Discussion
Macros are saved in modules with the workbooks in which they were written. Before you can run a macro, the workbook with the module containing the macro must be opened. When you select a macro name in the Run Macro dialog box, Excel performs the commands listed under the macro name in the module in sequence. Macros in any open workbook can be run from any other open workbook.
Excel versions 2000 - 03 only You can also run macros by clicking the Run Macro button on the Visual Basic toolbar .
Page 10
4. Select View Macros. 5. Select the macro you want to run. 6. Click Run.
6. Click the Relative Reference button Recording toolbar. 7. Record the steps of the macro.
on the Stop
on the Stop
Page 11
4. Click the Macros button again. 5. Select Record Macro.... 6. Type a name for the macro. 7. Record the steps of the macro. 8. Click the Stop button in the Status Bar when finished .
After recording a macro using relative references, ensure that you re-set the recorder if you wish to record your next macro using absolute references. In Excel 2000 - 03, this is achieved by clicking the Relative References button on the Stop Recording toolbar as soon as the recording starts but before carrying out any steps. Relative References active (background shading) Relative References not active (no background shading) In Excel 2007, this is achieved by opening the View Ribbon, clicking the Macros button and ensuring Use Relative References is correctly set before recording the new macro.
Page 12
workbook, you will not be able to, and a message will appear explaining how to save it correctly.
Page 13
In Excel 2000 03 you are warned about opening a workbook that contains macros by means of message boxes. Examples of these are shown below:
In Excel 2007, you are warned about opening a workbook that contains macros by means of a Notification in the Message Bar.
Page 14
Upon clicking the Options... button in the message bar, you are presents with a window offering choices on how to deal with the macro(s) contained in the workbook that you are trying to open. Examples are:
A digital signature is an electronic, encryption-based, secure stamp of authentication on a macro or document. This signature confirms that the macro or document originated from the signer and has not been altered. For further information about security settings and how to change them, see Appendix I on page 118.
Page 15
Page 16
Page 17
EXERCISE
RECORDING MACROS
1. Open a blank workbook. 2. Record a macro with absolute references as follows: Name: MyDataEntry Keystroke: Ctrl-Shift-R Store Macro in: Personal Macro Workbook Description: Sets up rep names and column labels
3. The macro should first add a new sheet to the workbook and then starting in cell A1, enter the data and formatting shown below.
Bold
Italic
4. Run the MyDataEntry macro using the assigned keystroke. Note how the data is entered into the same cells as when recorded. 5. Save the file as Sales Record and close. 6. Open the file Tables. 7. Select cell A1 on the Central Region sheet. 8. Record a macro with relative references as follows: Name: FormatHeading Keystroke: Ctrl-Shift-H Store Macro in: This Workbook. Description: Formats any five cell table heading
9. Start the recorder. 10. Click the appropriate Relative References button. 11. Format the currently selected cell with a bold font, a blue font colour and a top and bottom border.
Page 18
12. Select the cell to the right. 13. Repeat steps 11 and 12 for each cell until you get to the end of the row. 14. Stop the recorder. 15. Open the North Region sheet of the workbook. 16. Select cell B2. 17. Run the FormatHeading macro. If recorded correctly, the macro will format the top five cells of the table. 18. Repeat on the South Region sheet by selecting cell A4. 19. Save and close the file.
Page 19
The Visual Basic Editor can also be launched by using the shortcut keys: ALT + F11 (all versions), or by clicking the Visual Basic Editor button on the Visual Basic toolbar (Excel 2000 2003 only).
Page 21
Project Explorer
Code Pane
Properties Pane
If the Project Explorer pane and/or the Properties pane are not visible, click the Project Explorer button and/or the Properties button toolbar. on the VB Editor
The Project Explorer pane shows at the top level (in bold) all the open Excel files. They are normally listed as: VBAProject (file name).
Project Explorer pane showing top-level file names Any .XLA files in the Project Explorer pane are Add-Ins that have been installed to increase Excel functionality. They are normally password protected and cannot be viewed or edited. Examples of Add-Ins are: FUNCRES.XLA, SOLVER.XLA, and EUROTOOL.XLA. There may be many more, however, depending on your Excel setup. ). Once the file containing the macro(s) has been identified, you need to open its Modules folder, and finally open the specific module sheet containing the macro VBA code that you wish to edit. ).
Page 23
15. Double-click the module sheet containing the code. By selecting a macro in the Run Macro dialog box (see page 10) and clicking the Edit button, the Visual Basic Editor is launched and takes you directly to the module sheet containing the VBA code for the selected macro. The exception to this is the Personal Macro Workbook that has to be unhidden first (Window > Unhide)
Page 24
Page 25
A module sheet can also be copied to another workbook by clicking and dragging it from one workbook to another in the Project Explorer pane.
Page 26
Page 27
EXERCISE
USING THE VB EDITOR
1. Close any open files. 2. Open the files, Data Records and Sales Analysis. Enable macros, if prompted. 3. Launch the VB Editor. 4. Insert a module sheet into the Data Records workbook. 5. Rename the module sheet to FormattingMacros. 6. Open Module1 in the Sales Analysis workbook. 7. Copy the FormatTable macro. 8. Paste it into the FormattingMacros module of Data Records. 9. Return to Excel. 10. Save and close Data Records and Sales Analysis. 11. Open the file, Special Macros. Enable the macros, if prompted. 12. Launch the VB Editor. 13. Export the GeneralMacros1 module sheet as a file named GeneralMacros.txt. 14. Import the GeneralMacros1.txt file to the Personal Macro Workbook (personal.xls). 15. Remove the GeneralMacros1 module from the Special Macros workbook. Do not export it. 16. Move the GeneralMacros2 module sheet from Special Macros to the Personal Macro Worksheet by clicking and dragging it. 17. Close the VB Editor. 18. Exit Excel and save the Personal Macro Worksheet.
Page 28