Вы находитесь на странице: 1из 126

KEYTRAININGSOLUTIONSLTD

Microsoft Excel VBA Programming Introduction Student Edition

MicrosoftExcel IntroductiontoVisualBasicfor Applications(VBA) StudentEdition

FORCOURSEBOOKINGSANDGENERALENQUIRIES LONDON (020) 7417 0880

ABOUT KEY TRAINING SOLUTIONS LTD


Key Training Solutions Ltd, one of the largest training organisations in the UK, provides computer training products and services to help people use software so they can communicate, make decisions, and solve problems more effectively. The training materials are for the students' use both during the course and as a reference guide after the course has been completed. For more information on what Key Training Solutions may do for you, please visit us at our web site at www.keytraining.co.uk.

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.

COPYRIGHT & TRADEMARKS

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.

Key Training Solutions Limited

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

Key Training Solutions Limited

Page 4

LESSON 1 RECORDING MACROS


In this lesson, you will:
Record and run a macro Understand the difference between recording a macro in the Personal Macro Workbook or This Workbook Understand the difference between recording a macro with relative and absolute references

Introduction to Excel VBA

Lesson 1 Recording Macros

WORKING WITH VISUAL BASIC FOR APPLICATIONS


Discussion
With most Microsoft Office applications (Word, Access, PowerPoint, etc) , you can use the computer programming language Visual Basic for Applications (VBA) to enhance, customise and automate the tasks that you perform in the application. VBA can also be used to create import and export filters for various file formats. The word visual in Visual Basic refers to the way in which you develop the user interface for application. Buttons, dialog boxes, menus and so forth are drawn on the screen. The word basic in Visual Basic Applications refers to the programming code you write; Visual Basic is a form of the programming language BASIC (Beginners All-Purpose Symbolic Instruction Code). VBA should not be confused with VB (Visual Basic, which at the time of writing was at version 6.0) . VB allows programmers not only to create simple graphical user interface (GUI) applications, but also more complex ones. For users who do not have VB loaded on their computers, the code must be compiled into separate executable files. Code created in VBA can be run as part of the Excel application, without a separate executable file.

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.

Key Training Solutions Limited

Page 6

Introduction to Excel VBA

Lesson 1 Recording Macros

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

Introduction to Excel VBA

Lesson 1 Recording Macros

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.

The Record Macro dialog box (Excel 2000 - 03)

The Record Macro dialog box (Excel 2007)

Studying the Visual Basic code generated by the recorder is an excellent way of getting acquainted with the VBA language.

Procedures (Excel 2000 - 03)


1. Click the Tools menu. 2. Point at Macro 3. Select Record New Macro.... 4. Type a name for the macro (no spaces) in the Macro name: box. 5. Assign a keystroke in the Shortcut key: box, if desired. 6. Specify where to store the macro in the Store macro in: box. 7. Add additional information about the macro in the Description: box: 8. Click OK. and the word The Stop Recording toolbar appears Recording appears in the status bar at the bottom left of the Excel window .

Key Training Solutions Limited

Page 8

Introduction to Excel VBA

Lesson 1 Recording Macros

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)

The Visual Basic Toolbar

Procedures (Excel 2007)


1. Click the View tab on the Ribbon. 2. Click the Macros button in the Macro group. 3. Select Record Macro.... 4. Type a name for the macro (no spaces) in the Macro name: box. 5. Assign a keystroke in the Shortcut key: box, if desired. 6. Specify where to store the macro in the Store macro in: box. 7. Add additional information about the macro in the Description: box: 8. Click OK. A Stop button appears in the status bar at the bottom left of the Excel window .

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.

Key Training Solutions Limited

Page 9

Introduction to Excel VBA

Lesson 1 Recording Macros

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.

The Macro dialog box (Excel 2000 - 03)

The Macro dialog box (Excel 2007)

Procedures (Excel 2000 - 03)


1. Open a workbook and enable the macros. 2. Click the Tools menu. 3. Point to the Macros command. 4. Select Macros... in the side menu. 5. Select the macro you want to run. 6. Click Run.

Excel versions 2000 - 03 only You can also run macros by clicking the Run Macro button on the Visual Basic toolbar .

Procedures (Excel 2007)


1. Open a workbook and enable the macros. 2. Click the View tab on the Ribbon. 3. Click the Macros button in the Macro group.

Key Training Solutions Limited

Page 10

Introduction to Excel VBA

Lesson 1 Recording Macros

4. Select View Macros. 5. Select the macro you want to run. 6. Click Run.

RECORDING A MACRO USING RELATIVE REFERENCES


Discussion
By default, Excel records macros using absolute references. This means that it records the absolute or exact locations of any cells that you may select when recording your macro. For example, if you enter the text Annual Sales Report in cell A4, this will always be typed into cell A4 of a worksheet when you run the macro, irrespective of what cell was selected when you started. If you are using relative references, Excel records cell locations relative to the cell from which you start the macro. For example, if you enter the text Annual Sales Report into a cell when recording with relative referencing, you can reproduce this text in any cell of any worksheet by activating a cell and running the macro. Relative references give the macro more flexibility.

Procedures (Excel 2000 - 03)


1. Click Tools. 2. Point at Macro. 3. Select Record New Macro... from the side menu. 4. Type a name for the macro. 5. Click OK.

6. Click the Relative Reference button Recording toolbar. 7. Record the steps of the macro.

on the Stop

8. Click the Stop Recording button Recording toolbar when finished.

on the Stop

Procedures (Excel 2007)


1. Click the View tab on the Ribbon. 2. Click the Macros button in the Macro group. 3. Select Use Relative References from the menu.

Key Training Solutions Limited

Page 11

Introduction to Excel VBA

Lesson 1 Recording Macros

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.

Relative References active (orange shading)

Relative References not active (no orange shading)

SAVING A WORKBOOK CONTAINING A MACRO


Discussion
When you record a macro in This Workbook, the VBA code is written in a module in the workbook. When you save the workbook, therefore, you also save the module sheet and any macro(s) therein. In Excel 2007, workbooks containing macros have to be saved as a macro-enabled workbook. If you attempt to save a workbook containing macros as a standard Excel

Key Training Solutions Limited

Page 12

Introduction to Excel VBA

Lesson 1 Recording Macros

workbook, you will not be able to, and a message will appear explaining how to save it correctly.

Procedures (Excel 2000 03)


1. Record your macros in the workbook. 2. Click Save.

Procedures (Excel 2007)


1. Record your macros in the workbook. 2. Click the Microsoft Office Button. 3. Point at the Save As command. 4. Select Excel Macro-Enabled Workbook in the side menu. 5. Once the workbook has been saved in this way, it can later be updated using the standard Save command.

OPENING A WORKBOOK CONTAINING A MACRO


Discussion
While many macros are simply recordings of your keystrokes and mouse actions, VBA developers can write macros that carry out many commands on your computer. As a result, hackers can introduce harmful code onto your computer by writing macros that release a virus when run. When opening an Excel file containing macros, therefore, Excel uses various criteria to ensure that any macros contained therein are safe. The level and thoroughness at which Excel does this is determined by the security settings in force on your computer. The criteria for this varies depending on whether the workbook is being opened from a trusted location and/or if it is digitally signed. The level of security that Excel provides can be controlled. If youre creating your own macros, or the macros that you run are from a reliable source within your own workplace, youll probably want to lower the protective security settings. If, however, the macros you use are often received from unknown sources, you may wish to increase it. For further information about these setting and how to change then, see Appendix A Macro Security on page 118.

Key Training Solutions Limited

Page 13

Introduction to Excel VBA

Lesson 1 Recording Macros

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.

Excel 2007 window showing a macro security notification

Key Training Solutions Limited

Page 14

Introduction to Excel VBA

Lesson 1 Recording Macros

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.

Key Training Solutions Limited

Page 15

Introduction to Excel VBA

Lesson 1 Recording Macros

Procedures (Excel version 2000 - 03)


1. Click the File menu. 2. Select Open.... 3. Navigate to the drive/folder where the workbook is stored. 4. Select the file. 5. Click Open. 6. Note and respond to any message box that appears. 7. If no message box appears, you can assume that: The workbook contains no macro(s) The workbook contains macros but they are digitally signed from a trusted source The workbook is being opened from a trusted location. In Excel 2000 03, the only trusted location is the XLStart folder.

Procedures (Excel 2007)


1. Click the Microsoft Office button. 2. Select Open. 3. Navigate to the drive/folder where the workbook is stored. 4. Select the file. 5. Click Open. 6. Note any macro security notification that may appear in the message bar. 7. Click the Options... button in the message bar. 8. Note and respond to any message window that appears. 9. If no notification appears in the message bar, you can assume that: The workbook contains no macro(s) The workbook contains macros but they are digitally signed from a trusted source The workbook is being opened from a trusted location. In Excel 2007 there are several, default trusted locations. See page 122 for further information on how to use trusted locations.

Key Training Solutions Limited

Page 16

Introduction to Excel VBA

Lesson 1 Recording Macros

SAVING THE PERSONAL MACRO WORKBOOK


Discussion
The personal macro workbook is automatically created by Excel the first time you record a macro into it. It is then stored in the XLStart folder (a trusted location in all versions of Excel and part of your personal profile) and saved when you exit Excel. It is then automatically opened when you launch Excel; macros stored in it, therefore, ar e always available for use while Excel is running.

Procedures (All versions)


1. Exit Excel. 10. If macros have been recorded or edited in the personal macro workbook, the following message box appears:

11. Click Yes to save the macros or No to discard them.

Key Training Solutions Limited

Page 17

Introduction to Excel VBA

Lesson 1 Recording Macros

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.

Key Training Solutions Limited

Page 18

Introduction to Excel VBA

Lesson 1 Recording Macros

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.

Key Training Solutions Limited

Page 19

LESSON 2 THE VISUAL BASIC EDITOR


In this lesson, you will learn how to:
Launch the Visual Basic Editor Navigate the VB Editor screen Find a macro in the VB Editor Insert a module sheet into an Excel workbook Copy a module sheet between workbooks Rename a module sheet Delete a module sheet

Introduction to Excel VBA

Lesson 2 The Visual Basic Editor

LAUNCHING THE VISUAL BASIC EDITOR


Discussion
Before you can edit a macro, you need to find it. Similarly, if you wish to write a new macro from scratch, you need to access or create a module in which to store the code. All this can be done in the Visual Basic Editor (VBE). The VBE is a program that sits alongside the Office family of applications and can be launched from within most Office programs. The VBE is not unique to Excel, you can use it in most Office programs to create VBA code in order to automate and customise the application.

Procedures (Excel 2000 - 03)


1. Open the workbook. 2. Enable the macros, if necessary. 3. Click Tools. 4. Point at Macro X. 5. Select Visual Basic Editor from the side menu.

Procedures (Excel 2007)


1. Open the workbook. 2. Enable the macros, if necessary. 3. Check the Ribbon to see if there is a Developer tab. If there is, proceed to step 9. If there is not, continue with step 4. 4. Click the Microsoft Office Button. 5. Click the Excel Options button. 6. Select Popular in the pane at the left, if necessary. 7. Click the Show Developer tab in the Ribbon check box. 8. Click OK. 9. Click the Developer tab on the Ribbon. 10. Click the Visual Basic button in the Code group.

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

Key Training Solutions Limited

Introduction to Excel VBA

Lesson 2 The Visual Basic Editor

NAVIGATING THE VISUAL BASIC EDITOR


Discussion
The Visual Basic Editor consists of four main sections: ). Menus and Toolbar(s) provide methods for giving commands to the editor. The Project Explorer pane shows all open Excel workbooks files and Add-Ins. Primarily used for locating files and accessing locations where VBA code is stored. ). The Properties pane primarily used for adding additional characteristics and settings to objects on User Forms and/or for naming module sheets. ). The Code Pane primarily a simple word-processor used for writing and editing the VBA code on a selected module sheet).
Menus and Toolbar

Project Explorer

Code Pane

Properties Pane

The Visual Basic Editor

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

FINDING A MACRO IN THE VISUAL BASIC EDITOR


Discussion
Before you can edit a macro, you need to navigate to where it is stored. The Project Explorer pane in the VBE can be used for this purpose. ).
Key Training Solutions Limited Page 22

Introduction to Excel VBA

Lesson 2 The Visual Basic 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. ).

Project Explorer showing the contents of a workbooks Modules folder

Procedures (All versions)


1. Launch the Visual Basic Editor. 12. Show the Project Explorer pane, if necessary. 13. Click the button at the left of the file (VBAProject) containing the macro(s).

Key Training Solutions Limited

Page 23

Introduction to Excel VBA

Lesson 2 The Visual Basic Editor

14. Click the

at the left of the Modules folder. ).

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)

INSERTING A MODULE INTO A WORKBOOK


Discussion
If writing a new macro into a workbook and there is no module sheet already in it to use, you need to insert one. ). There are no hard and fast rules about how many module sheets are used in a workbook. Macros can be written on an existing module sheet where previous ones have been recorded or written, or new module sheets can be added to keep different types of macro separate in the same way as normal worksheets in Excel are used to organise and arrange your work more clearly.

Procedures (All versions)


1. Open the workbook. 2. Enable the macros, if necessary. 3. Launch the Visual Basic Editor. 4. Select in the Project Explorer pane the workbook (VBAProject) that you want to add the module sheet to. 5. Click the Insert menu. 6. Select Module. A module sheet can also be inserted into a workbook by right-clicking the workbook in the Project Explorer, pointing at Insert X and selecting Module from the side menu.

Key Training Solutions Limited

Page 24

Introduction to Excel VBA

Lesson 2 The Visual Basic Editor

COPYING A MODULE BETWEEN WORKBOOKS


Discussion
There may be times when you need to transfer macros between workbooks. For example, there may be macros in a workbook that would also be useful in another workbook, or it may just be that you recorded or wrote a macro in the wrong module and need to move it. While it is possible to copy a macro from one module and paste it into another, it may be easier and more convenient to copy the whole module. This can be achieved in the VB Editor by exporting the module, and importing it into the other workbook.

Procedures (All versions)


1. Launch the VB Editor. 2. In the Project Explorer, right-click the module that you wish to copy to another workbook. 3. Select Export File.... 4. Type a file name for the module. 5. Select a location to store the file. 6. Click Save.

Key Training Solutions Limited

Page 25

Introduction to Excel VBA

Lesson 2 The Visual Basic Editor

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.

RENAMING A MODULE SHEET


Discussion
A default name of Module[n] is given to all new module sheets whether they are added by the macro recorder or by the user (see page 24). It may be necessary, therefore, to rename module sheet(s) to clarify what macros they contain.

Procedures (All versions)


1. Launch the VB Editor. 2. In the Project Explorer, select the module that you wish to rename. 3. Click into the Name box of the Properties pane. 4. Type a name for the module sheet. 5. Press Enter.

Key Training Solutions Limited

Page 26

Introduction to Excel VBA

Lesson 2 The Visual Basic Editor

DELETING A MODULE SHEET


Discussion
Module sheets can be removed from the workbook if no longer required. When removing a module sheet, you are given the option of saving it as a text file. This stores the code so that it can be imported back into the workbook, or into another one, at a later date.

Procedures (All versions)


1. Launch the VB Editor. 2. In the Project Explorer, right-click the module that you wish to delete. 3. Select Remove Module[n].... 4. Click Yes to save the module as a text file or, click NO to discard.

Key Training Solutions Limited

Page 27

Introduction to Excel VBA

Lesson 2 The Visual Basic Editor

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.

Key Training Solutions Limited

Page 28

LESSON 3 ASSIGNING MACROS


In this lesson, you will learn how to:
Assign a macro to a keystroke Assign a macro to a custom toolbar button Create a new toolbar Assign a macro to a menu command Create a new menu Delete a custom toolbar button Delete a macro command from a menu Create a worksheet macro button Delete a worksheet macro button

Introduction to Excel VBA

Lesson 3 Assigning Macros

ASSIGNING A SHORTCUT KEY


Discussion
You can assign a shortcut key to a macro. When a macro has a shortcut key, pressing the shortcut key combination runs the macro. All macro shortcut key combinations consist of [Ctrl] followed by a letter. Shortcut keys are case sensitive. Therefore the shortcut Key [Ctrl+e] is not the same as the shortcut Key [Ctrl+Shift+E].

Shortcut Keys can be assigned when you record a macro by entering a shortcut key in the Record Macro dialog box. You should avoid assigning shortcut Keys to macros that are the same as the standard Excel shortcuts (e.g., [Ctrl+B], [Ctrl+S]) because the standard Excel shortcuts will be overridden by the macro shortcuts.

Procedures (Excel 2000 - 03)


1. Open the workbook containing the macros. 16. Enable the macros, if necessary. 17. Click the Tools menu. 18. Point to the Macro command. 19. Select Macros... in the side menu. 20. Select the name of the macro to which you want to assign the shortcut key. 21. Click Options. 22. Type a letter. 23. Select OK. 24. Select the Close button in the Macro dialog box.

Procedures (Excel 2007)


1. Open the workbook containing the macros. 25. Enable the macros, if necessary. 26. Click the View tab on the Ribbon. 27. Click Macros in the Macro group. 28. Select View Macros.

Key Training Solutions Limited

Page 30

Introduction to Excel VBA

Lesson 3 Assigning Macros

29. Select the name of the macro to which you want to assign the shortcut key. 30. Click Options. 31. Type a letter (preferably in conjunction with the SHIFT key). 32. Click OK. 33. Click the Close button in the Macro dialog box.

The Macro Options dialog box (Excel 2003 shown but almost identical in all versions)

ADDING A CUSTOM TOOLBAR BUTTON (EXCEL 2000 - 03 ONLY)


Discussion
In addition to the toolbar buttons that execute commands, Excel provides generic buttons that you can customise by attaching a macro. These buttons are listed in the Commands list box in the Customize... dialog box. Because custom toolbar buttons are saved with the Excel application and hence always available, the are best used to run general-purpose macros that you have stored in the personal macro workbook.

Procedures
1. Open the workbook containing the macro(s). If the macros are in the personal macro workbook, it will already be open. 34. Click Tools. 35. Select the Customize... command. 36. Open the Commands tab. 37. Select Macro from the Categories list box. 38. Drag the Custom Button location on one of your existing toolbars. to a convenient

Key Training Solutions Limited

Page 31

Introduction to Excel VBA

Lesson 3 Assigning Macros

39. Right-click the custom button that you have added to your . toolbar and type a descriptive name for it This name will be used as the Help Tip when you later point at the button to use it. 40. Select Change Button Image or Edit Button Image... to modify the appearance of the button, if necessary. 41. Right-click the custom button and select Assign Macro... . 42. Select the macro to assign to the custom button. 43. Click OK. 44. Click Close in the Customize dialog box.

The Customize dialog box with the Commands tab open

ADDING A MACRO BUTTON TO THE QUICK ACCESS TOOLBAR (EXCEL 2007 ONLY)
Discussion
In addition to the Ribbon buttons that execute commands, Excel 2007 provides buttons for your macros that can be added to the Quick Access Toolbar. These buttons can be found in the Customize... pane of Excel Options. Custom buttons on the Quick Access Toolbar are saved with the Excel application and hence always available. They are best used to run general-purpose macros that you have stored in the personal macro workbook.

Procedures
1. Open the workbook containing the macro(s). If the macros are in the personal macro workbook, it should already be open.

Key Training Solutions Limited

Page 32

Introduction to Excel VBA

Lesson 3 Assigning Macros

2. Click the Customize Quick Access Toolbar button . 3. Select More Commands.... 4. Select Macros in the Choose commands from: drop down list. 5. Select the macro that you wish to assign a custom button to in the list below. 6. Click Add >>. 7. Select the macro name in the list at the right. 8. Click the Modify... button to change the button image, if desired. 9. Click OK. 10. Click OK.

The Customize pane of the Excel Options dialog box showing list of macros (Excel 2007)

CREATING A NEW TOOLBAR (EXCEL 2000 - 03 ONLY)


Discussion
As well as adding custom buttons to existing toolbars, you can create a new toolbar. If you have many macros to create custom buttons for, it makes sense to add them to a separate toolbar rather than fill the existing toolbars to overflowing.

Procedures
1. Open the workbook containing the macro(s). If the macros are in the personal macro workbook, it will already be open. 45. Click Tools.

Key Training Solutions Limited

Page 33

Introduction to Excel VBA

Lesson 3 Assigning Macros

46. Select the Customize... command. 47. Open the Toolbars tab, if necessary. 48. Click the New... button. 49. Type a descriptive name for the new toolbar. 50. Click OK. A small, empty toolbar appears in the centre of the screen. 51. Add custom buttons to the new toolbar as described on page 31. Custom buttons that you may have already added to existing toolbars can also be moved (click and drag) to the new toolbar. The Customize... window MUST be open in order to do this, even if you are not doing anything inside it. 52. Click Close in the Customize dialog box when finished.

ASSIGNING A MACRO TO A MENU (EXCEL 2000 - 03 ONLY)


Discussion
You can assign a macro to a menu. You can choose in which menu you want the macro to appear. The macro appears as a menu command item to which you can give a specific name. Whenever the workbook containing the macro is opened, you can execute the macro, just as you would execute any standard menu command.

It may be necessary to move the Customise dialog box in order to drag Custom Menu Item from the Commands list box to the desired location on the menu.

Procedures
1. Open the workbook containing the macro(s). If the macros are in the personal macro workbook, it will already be open. 53. Enable the macros, if necessary. 54. Click Tools. 55. Select the Customize... command. 56. Select the Commands tab. 57. Select Macros from the Categories list box.

Key Training Solutions Limited

Page 34

Introduction to Excel VBA

Lesson 3 Assigning Macros

58. Drag Custom Menu Item from the Commands list box to the menu that you wish to add it to (eg. Tools); keep them mouse button held down and the menu will open. 59. Click and drag the custom menu item down into the menu to the desired location. 60. Right-click the custom menu that you have added to your menu. 61. Type a descriptive name for it in the Name: box. This name will show up as the command when you later use the menu. Tip: Type an ampersand (&) immediately before the character that you want to underline and make the shortcut key for the item . 63. Select the macro to assign to the menu item. 64. Click OK. 65. Click Close in the Customize dialog box. . 62. Right-click the custom menu item and select Assign Macro...

CREATING A NEW MENU (EXCEL 2000 - 03 ONLY)


Discussion
As well as adding custom menu items to existing menus, you can create a new menu. If you have many macros to create menu items for, it makes sense to add them to a separate menu rather than fill the existing menus to overflowing.

Procedures
1. Open the workbook containing the macro(s). If the macros are in the personal macro workbook, it will already be open. 66. Click Tools. 67. Select the Customize... command. 68. Open the Commands tab. 69. Select New Menu in the Categories list box. 70. Click and drag New Menu  from the commands list box at to a convenient position on the the right menu bar (eg. between Window and Help). 71. Release the mouse button.
Key Training Solutions Limited Page 35

Introduction to Excel VBA

Lesson 3 Assigning Macros

72. Right-click the new menu and type a descriptive name for the menu in the Name: box (eg. Macros). Tip: Type an ampersand (&) immediately before the character that you want to underline and make the shortcut key for the . menu 73. Add custom menu items to the new toolbar as described on page 34. Custom menu items that you may have already added to existing menus can also be moved (click and drag) to the new menu. The Customize... window MUST be open in order to do this, even if you are not doing anything inside it. 74. Click Close in the Customize dialog box when finished.

DELETING A CUSTOM TOOLBAR BUTTON OR CUSTOM MENU ITEM (EXCEL 2000 - 03 ONLY)
Discussion
Once you assign a macro to a custom toolbar button or a custom menu item, the macro is available to all worksheets. If you no longer want to run the macro in this way, you can delete the commands. Macro items can also be deleted from menus and toolbars by selecting opening the Customize... dialog box, and dragging the button or menu item off the toolbar or menu.

Procedures
1. Click the Tools menu. 2. Select the Customize... command. 3. Right-click the toolbar button that you want to delete. 4. Select Delete. 5. Click the menu containing the macro you want to delete. 6. Right-click the menu item that you want to delete. 7. Select Delete. 8. Click Close in the Customize... window.

Key Training Solutions Limited

Page 36

Introduction to Excel VBA

Lesson 3 Assigning Macros

USING A MACRO BUTTON


Discussion
You can create macro buttons in a worksheet that, when clicked, runs a particular macro. Macro buttons can simplify your work, automate repetitive tasks, or help an inexperienced user perform various worksheet tasks. You can draw macro buttons anywhere on a worksheet. Like other graphic objects, macro buttons float above the worksheet. You can create as many macro buttons as desired to perform a number of different tasks.

Procedures (All versions)


1. Open the workbook. 75. Enable the macros. 76. Click the macro button.

CREATING A MACRO BUTTON


Discussion
You create a macro button on a worksheet using the Forms toolbar. You can also size the macro button and position it anywhere on the worksheet. After you draw the button, the Assign Macro dialog box opens in which you assign a macro to the button. When the button is clicked, the macro attached to the button runs.

Creating a macro button (Excel 2000 - 2003)

Procedures (Excel 2000 - 03)


1. Open the workbook. 77. Enable the macros, if necessary.
Key Training Solutions Limited Page 37

Introduction to Excel VBA

Lesson 3 Assigning Macros

78. Open the worksheet that you want to create the macro button on. 79. Click the View menu. 80. Point at Toolbars. 81. Select Forms from the side menu. 82. Click the Button button on the Forms toolbar.

83. Click and drag to create a button in a blank part of the worksheet. 84. Release the mouse button. 85. Select the macro you want to assign to the button. 86. Click OK. 87. Click and drag to select the text on the button. 88. Release the mouse button. 89. Type the new text. 90. Deselect the button by clicking a cell on the worksheet.

Procedures (Excel 2007)


In order to create a worksheet button in Excel 2007, an extra tab has to be added to the Ribbon - the Developer tab.

The Excel 2007 Developer tab 1. Open the workbook. 2. Enable the macros, if necessary. 3. Click the Office Button. 4. Click Excel Options. 5. Select the Show Developer tab in the Ribbon check box. 6. Click OK. 7. Click the Developer tab on the Ribbon.

8. Click the Insert button in the Controls group

Key Training Solutions Limited

Page 38

Introduction to Excel VBA

Lesson 3 Assigning Macros

9. Click the Button (Form Control) button 10. Click and drag to create a button in a blank part of the worksheet. 11. Release the mouse button. 12. Select the macro you want to assign to the button. 13. Click OK. 14. Click and drag to select the text on the button. 15. Release the mouse button. 16. Type the new text.

17. Deselect the button by clicking a cell on the worksheet.

COPYING A WORKSHEET MACRO BUTTON


Discussion
You can create macro buttons quickly by copying existing ones. This option is useful if you need several similar macro buttons on a worksheet. When you copy macro buttons, you can ensure that the buttons are the same size and shape.

Copying a macro button (Excel 2003 shown but techniques identical in all versions)

Procedures (All versions)


1. Open the workbook. 91. Enable the macros, if necessary.
Key Training Solutions Limited Page 39

Introduction to Excel VBA

Lesson 3 Assigning Macros

92. Right-click the button you want to copy. 93. Select Copy. 94. Right-click a blank cell where you want to make the copy. 95. Select Paste. 96. Right-click the edge of the copied button to display the shortcut menu. 97. Select the Assign Macro... command. 98. Select the macro you want to assign to the button. 99. Click OK. 100. 101. 102. 103. Click and drag to select the text on the button. Release the mouse button. Type the new text. Deselect the button by clicking a cell on the worksheet.

EDITING A WORKSHEET MACRO BUTTON


Discussion
You can move, size or format a macro button the same way that you move, size or format other graphic objects on a worksheet. In order edit a macro button, you must first select it.

Moving a macro button (Excel 2003 shown but techniques identical in all versions)

Key Training Solutions Limited

Page 40

Introduction to Excel VBA

Lesson 3 Assigning Macros

Sizing a macro button (Excel 2003 shown but techniques identical in all versions) To select a macro button for moving or sizing, you hold the [Ctrl] Key, click the desired macro button, and release the [Ctrl] Key. If you do not select the button first (if selection handles do not appear around the button), the macro attached to the button runs when you click it.

Procedures (All versions)


1. Open the workbook. 2. Enable the macros. 3. To move the macro button, hold Ctrl and click the button to select it. 4. Release the Ctrl key. 5. Point at the shaded edge you want to move. 7. Release the mouse button. 8. To size the macro button, hold Ctrl and click the button to select it. 9. Release the Ctrl key. 10. Point to one of he sizing handles you want to size. 11. Drag the handle to size the button. 12. Release the mouse button. 13. To format a macro button, right-click it to show its shortcut menu. 14. Select Format Control....
Key Training Solutions Limited Page 41

of the button that

6. Click and drag the button to a new position on the worksheet.

on the button that

Introduction to Excel VBA

Lesson 3 Assigning Macros

15. Make changes as necessary. 16. Click OK. 17. Click any cell on the worksheet to deselect.

The Format Control dialog box (Excel 2000 - 2003)

The Format Control dialog box (Excel 2007)

DELETING A MACRO BUTTON


Discussion
You can delete any macro buttons you no longer need. This option prevents you from accidentally using macros that no longer work correctly. When you delete a macro button, only the button itself is deleted. The attached macro is not deleted.

Procedures (all versions)


1. Open the workbook. 104. 105. 106. 107. Enable the macros, if necessary. Hold Ctrl and click the macro button to select it. Release the Ctrl key. Press the Delete key.

Key Training Solutions Limited

Page 42

Introduction to Excel VBA

Lesson 3 Assigning Macros

EXERCISE
ASSIGNING MACROS
1. Open the file Run Macros. Enable the macros, if prompted. This workbook contains several macros that apply different number styles. 2. On the Qtr 1 sheet of the workbook, assign all the macros stored in the workbook to worksheet buttons (use the Forms toolbar). The picture below gives you a guide to what is required.

3. Select the range C4:F9 and run the SterlingStyle macro using the worksheet button. 4. Select the range C14:F19 and run the PlainStyle macro using the worksheet button. 5. On the same range, run the NumberStyle macro using the worksheet button. 6. Select the ranges C3:E3 and C13:E13 and run the DateStyle macro using the worksheet button. 7. Assign the macros in this workbook to keystrokes as follows: SterlingStyle: Ctrl Shift Y PlainStyle: Ctrl Shift L NumberStyle: Ctrl Shift N DateStyle: Ctrl Shift - T

8. Repeat the instruction from 3 to 6 above on the Qtr 2 sheet using the appropriate keystrokes. Ensure the macros run correctly. 9. Save and close the file. 10. Open the file, Run More Macros.

Key Training Solutions Limited

Page 43

Introduction to Excel VBA

Lesson 3 Assigning Macros

11. Excel 2000 03 users only: Create a new toolbar named My Macros. Excel 2007 users: Go to next step 12. Excel 2000 03 users: Add custom buttons to this toolbar to run the WrapAndCentre and ToggleGrid macros that are stored in the Personal Macro Workbook. Excel 2007 users: add custom buttons to the Quick Access Toolbar to run the WrapAndCentre and ToggleGrid macros that are stored in the Personal Macro Workbook. 13. Run the ToggleGrid macro using the custom button. 14. Select the range A4:A10 and run the WrapAndCentre macro with the custom button. 15. Excel 2000 03 users: Delete the My Macros toolbar. Excel 2007 users: Remove the custom macro button from the Quick Access Toolbar. 16. Save and close the file.

Key Training Solutions Limited

Page 44

LESSON 4 WRITING PROCEDURES


In this lesson, you will learn how to:
Understand the difference between Objects, Methods and Properties Write basic VBA statements in a procedure Deal with a Run-Time error Work with the Object Browser

Introduction to Excel VBA

Lesson 4 Writing Procedures

INTRODUCTION TO EXCEL OBJECTS


Discussion
An object is something that can be controlled by VBA, for example a worksheet or a range of cells. An object is controlled by using methods and properties. Putting it simply, an object is an Excel thing that you want to work with. A method is an action that you want to perform on the object and a property is something about the object that you want to change. You can also get objects to tell you things about themselves by returning their properties and in certain cases, their methods. An analogy would be: Object = Dog Properties = Colour of fur; weight; height; length of tail! etc. Methods = Bark; walk; eat; beg! etc. Most VBA statement (lines of code) that carry out an action always start with the object that you want to do something to or with. This is then followed by a dot (full stop), and that is then followed by an appropriate method or property. Hence: Dog.Bark (make the dog bark) Dog.Eat (make the dog eat) Dog.ColourOfFur = Brown (make the colour of the dogs fur brown) The Excel Object Model is a hierarchy of objects that you can work with in Excel. In Excel 2003 there are approximately 200 objects, although about 60 of them are available only for backward compatibility with previous versions. Every new version of Excel introduces new ones, and in Excel 2007 there are approximately 250. A useful link to follow (current at April 2009) if you wish to learn more about the Excel Object Model is: http://msdn.microsoft.com/en-us/library/bb149081.aspx It is not necessary to know all the Excel objects; very effective procedures can be written for most everyday purposes using only a few. Some of the more common, user-interface objects are: Object Application Workbooks Refers to The entire Microsoft Excel application. A collection of all the Workbooks that are currently open in the Excel application.

Key Training Solutions Limited

Page 46

Introduction to Excel VBA

Lesson 4 Writing Procedures

Worksheets

A collection of all the Worksheets in the specified or active workbook. Worksheets are specifically sheets consisting of columns and rows and used for entering and working with data. Represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3-D range. Worksheets refers specifically to a standard Excel worksheet, viz. one containing columns and rows. If the workbook that you are referring to contains chart sheets or special module and dialog sheets, the Sheets object should be used.

Range

Examples of using the above objects are: Application.Quit (exit Excel) Range(A1).Value = Excel VBA (write Excel VBA in cell A1) Range(A1:A10).Copy (copy onto the clipboard the contents of the range A1:A10)

Discussion
Collections
You will notice that a couple of the objects in the above list are plural (viz. Workbooks and Worksheets). This is because they are collections and when used, apply whichever method that follows to ALL the open objects that they refer to, for example: Workbooks.Close (close ALL open workbooks) Workbooks.Save (save ALL the open workbooks) Worksheets.PrintOut (print ALL the worksheets in the workbook) Worksheets.Add (insert a new worksheet into the workbook) Range is also a collection (a collection of cells) although it is written in the singular.

Key Training Solutions Limited

Page 47

Introduction to Excel VBA

Lesson 4 Writing Procedures

Returning Objects from Collections


You may have several workbooks open, but you want your macro to identify and carry out tasks on just one of them. You may have a workbook open with many worksheets in it, and you want your macro to carry out tasks on just a couple of them. In all these case, you have to refer to the collection (Workbooks or Worksheets) and then add in brackets, the name or index number of the specific one that you want the macro to refer to. If you are using the name of the object, it must be written in quotes (). If you are referring to it by its index number, the number does NOT go inside quotes. For example:

Referring by name
WorkBooks(Sales Analysis).Activate (activate the open workbook named Sales Analysis) WorkSheets(Sheet2).Activate (activate the worksheet in the current workbook named Sheet2)

Referring by index number


The index number of a workbook is automatically applied by Excel in the order that it is opened or created. The first workbook will always have an index number of 1, irrespective of its saved name. In Excel 2000 2003, the index number of a workbook can be identified by clicking the Window menu.

Workbook index numbers (Excel 2000 2003) In Excel 2007 the index number of a workbook can be identified by clicking the View tab on the Ribbon and clicking the Switch Windows button

Workbook index numbers (Excel 2007) Eg: WorkBooks(1).Activate or WorkBooks.Item(1).Activate (activate the open workbook with an index number of 1)

Key Training Solutions Limited

Page 48

Introduction to Excel VBA

Lesson 4 Writing Procedures

The index number of a worksheet is as it appears from left to right. The worksheet at the left of the workbook will always have an index number of 1, irrespective of its name. Eg: Worksheets(2).Activate or Worksheets.Item(2).Activate (activate the second worksheet from the left of the current workbook) The object - Range - is also a collection (a collection of cells) although it is written in the singular. To return a single range object, you refer to it by its absolute reference, eg: Range(C10).Select (select the cell C10) You cannot refer to a cell by its index number using range. To refer to a cell by its index number, use Cells, eg: Cells(1).Select (select the cell A1) Cells(257).Select (select the cell A2) Cells are indexed starting in the top left corner of the worksheet (A1) and going across the rows and down the columns, hence A1 = Cells(1); B1 = Cells(2), C1 = Cells(3).... etc. Cells can more easily be used by referencing their row number and column number, eg: Cells(1,1).Value = Excel VBA (enter Excel VBA in cell A1 -row 1 columm1 ) Cells(2,1).Font.Bold = true (make bold the font in cell A2 - row 2 column 1) or Cells.Item(257).Select or Cells.Item(1).Select

METHODS AND PROPERTIES


Discussion
A method is an action that can be performed by the object. For example, a worksheet has an Insert method to insert rows or columns. A property is a characteristic of the object that can be set in a particular way. For example a Font has many properties, such as, size, colour, bold, italic, etc. a range of cells has a height property. There may be dozens of objects in Excel, but there are hundreds of methods and properties. The actions that they perform will also vary depending on the object that

Key Training Solutions Limited

Page 49

Introduction to Excel VBA

Lesson 4 Writing Procedures

they are being used with. The Add method, for example, can be used in Excel 2007 with about 44 different objects! It is not necessary to know all the different methods and properties associated with each object in order to write useful and effective code. Listed below are some of the more popular methods and properties used in conjunction with the objects given on page 46. Object Application Methods(M) and Properties (P) Quit (M) ScreenUpdating (P) Sample Code Application.Quit (exit Excel) Application.ScreenUpdating = False (screen updating is turned off to speed up your macro code. You won't be able to see what the macro is doing, but it will run faster) Application.DisplayAlerts = False (disables Excel from displaying certain alerts and messages when a macro is running. If a response is required at any time, Microsoft Excel chooses the default response. The exception to this rule is Save As where the default is No but Excel picks Yes to overwrite the existing file) Workbooks Add (M) PrintOut (M) Workbooks.Add (adds a new workbook to the Excel application) Workbooks.PrintOut (prints all open workbooks completely) Workbooks(Sales Analysis).PrintOut (prints the workbook named Sales Analysis) Save (M) Close (M) Workbooks(Sales Analysis).Save (saves (updates) the workbook named Sales Analysis) Workbooks.Close (closes all the open workbooks) Workbooks(Sales Analysis).Close (closes the workbook named Sales Analysis) Worksheets Add (M) Worksheets.Add (adds a new worksheet to the left of the current worksheet in the current workbook) Worksheets(1).Activate (makes the first sheet at the left of the workbook, the active worksheet) Worksheets(London Data).Delete (delete the sheet in the current workbook named London Data)

DisplayAlerts (P)

Activate (M)

Delete (M)

Key Training Solutions Limited

Page 50

Introduction to Excel VBA

Lesson 4 Writing Procedures

Object

Methods(M) and Properties (P) Name (P) PrintOut (M)

Sample Code Worksheets(Sheet1).Name = 2009 Sales (renames the sheet named Sheet1 to 2009 Sales) Worksheets(Summary).PrintOut (print the sheet in the current workbook named Summary) Range(A1:C10).Select (select the range A1 to C10) Range(B20).Clear (clear cell B20 of both contents and formatting) Range(B20).ClearContents (clear cell B20 of just contents) Range(B20).ClearFormatting (clear cell B20 of just formatting) Range(A1).Value = Summary Sheet (write the text Summary Sheet in cell A1) Range(A6).Formula = =sum(A2:A5) (enter the formula SUM(A2:A5) in cell A6) Range(D10).FormulaR1C1 = =R[-2]C R[-1]C (enter a formula in cell D10 that subtracts the cell one row up in the same column from the cell that is two cells up in the same column. This is equivalent to =D8-D9) The Font property cannot be used on its own and needs to be elaborated with additional properties. Eg. Range(A1).Font.Bold = True (makes the font in cell A1 Bold) Range(A1).Font.Italic = True (makes the font in cell A1 Italic) Range(A1).Font.Underline = True (makes the font in cell A1 underlined) Range(A1).Font.Size = 18 (makes the font in cell A1 18pts) Range(A1).Font.Name = Arial Black (makes the font in cell A1 Arial Black) Range(A1).Font.ColorIndex = 15 (makes the font in cell A1 mid grey)

Range

Select (M) Clear (M) ClearContents (M) ClearFormatting (M) Value (P) Formula (P) FormulaR1C1 (P)

Font (P)

Interior
Key Training Solutions Limited

Range(A1).Font.Color = vbBlue (makes the font in cell A1 blue)

Page 51

Introduction to Excel VBA

Lesson 4 Writing Procedures

Object

Methods(M) and Properties (P) PrintOut (M)

Sample Code Range(A1:A8).Interior.Color = vbYellow (makes the fill colour in cells A1 to A8 yellow) Range(A1:D20).PrintOut (prints just the range A1 to D20 on the current sheet)

RETURNING METHODS AND PROPERTIES


Discussion
The previous section of this lesson dealt primarily with applying methods and setting properties to objects. There are cases, however, where a method or more commonly, a property, needs to feed back to the macro (return), information about an object. This is useful in decision-making control structures (see Lesson 5 Control Structures, on page 72), where the flow of the code needs to change based on conditions or tests found in the workbook. Returning is also useful for counting objects in collections so that code can be run an appropriate number of times on the appropriate number of items. The current value of a method or property is often saved as a variable (see Lesson 6 Data Variables on page 86). The examples below gives code for returning: a) whether the font in a cell is bold b) if the gridlines on a worksheet are turned on c) the number of sheets in a workbook, and d) the number of cells in a selected range. a) var1 = ActiveCell.Font.Bold The value of var1 will be either TRUE or FALSE based on whether the font in the active cell is bold. b) var2 = ActiveWindow.Gridlines The value of var2 will be either TRUE or FALSE based on whether the worksheet gridlines are turned on or off. c) var3 = ActiveWorkbook.Sheets.Count (can be shortened to Sheets.Count) The value of var3 will be however many sheets (of all types) there are in the active workbook.

Key Training Solutions Limited

Page 52

Introduction to Excel VBA

Lesson 4 Writing Procedures

d) var4 = Range(A1:G30).Cells.Count The value of var4 will be 210, the number of cells in the range A1 to G30.

ADDING ARGUMENTS TO METHODS


Discussion
While many methods can be used without additional information (arguments), they will provide just a standard, default functionality. Adding additional arguments can make a Method more powerful. Some methods MUST have additional arguments added, and others can have NO additional arguments added. Worksheets.Add will insert a default new worksheet to the left of the current one in the same way as if you use Insert > Worksheet in Excel 2000 2003, or use the Home tab, Insert button, Insert Sheet in Excel 2007. By adding additional arguments to the Add method, it can do more. The easiest way of finding out what additional arguments can be used with a method is to type a space after it. By typing Worksheets.Add followed by a space into a module, the following Auto Quick Info Tip appears.

The additional parameters are as follows: Name Before After Count Type Required/ Optional Optional Optional Optional Optional Description An object that specifies the sheet before which the new sheet is added. An object that specifies the sheet after which the new sheet is added. The number of sheets to be added. The default value is one. Specifies the sheet type. Can be one of the following: xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a sheet based on an existing template, specify the path to the template. The default value is xlWorksheet.

All the additional arguments in this case are optional. If, however, you wanted to add three new sheets before the first one at the left , the syntax would be as follows:

Key Training Solutions Limited

Page 53

Introduction to Excel VBA

Lesson 4 Writing Procedures

Space

After argument (2nd) (here left blank)

Sheets.Add Sheets(1), , 3
Object Method Before argument (1st) Count argument (3rd)

There must be a space before the word Add and the first argument. The first argument describes the object before which you want to add the new sheet (Sheets(1)). The second argument is not required and left blank by typing commas with nothing between them. The third argument is the number of sheets to insert. The final argument, if not used, should be omitted. Do not add any further commas.

An alternative syntax that makes method arguments easier to use and understand uses named arguments. In the above example, the syntax would be as follows: Sheets.Add Before:=Sheets(Sheet1), Count:= 3 A space still needs to be added after the word Add, but the additional arguments that you want to use are typed exactly as they appear in the Auto Quick Info Tip immediately followed by a colon and an equal symbol (:=) and then their value. This not only makes it clearer to read and understand, but by only entering the arguments that you need, keeps the statement more concise. Another example of a method with an optional argument is Copy (or Cut): Range(A1:A10).Copy Destination:= Sheets(2).Range(B1) That is certainly easier, quicker and more understandable than typing the following: Range(A1:A10).Copy Sheets(2).Activate Range(B1).Select Activesheet.Paste An example of a method that needs a mandatory argument is Open when it refers to the Workbooks object. Without the Filename argument, Excel would not know which file you wanted to open! Eg: Workbooks.Open Filename:= s:\SharedData\Excel\Sales.xls
Key Training Solutions Limited Page 54

Introduction to Excel VBA

Lesson 4 Writing Procedures

A full list of arguments for the Open method (Excel 2003) is:

PROPERTIES THAT ARE ALSO OBJECTS


Discussion
As briefly described on page 46, the Excel Object Model is a hierarchy of objects that you can manipulate in VBA. At the top of the hierarchy is the Application object, which has many methods and properties that it can manipulate. Some of its properties are also objects in their own right (think of them as sub-objects) and some of these have properties that are objects in their own right too (think of them as sub-sub-objects). For example, to enter a formula into cell B10, you could write: Application.ActiveWorkbook.ActiveSheet.Range(B10).Formula = =B9 * B8) Entering such a long statement would be very time consuming and make for unwieldy, unnecessarily complicated code that could be difficult to understand and prone to errors. It is, therefore, usually abbreviated to the object at the lowest level, viz. Range. Hence, a more concise statement for carrying out the same action would be: Range(B10).Formula = =B9 * B8 This assumes that you want to enter the formula in cell B10 of the sheet that the macro is being run from (the active sheet). If, however, you wish to enter the formula into cell B10 of Sheet2 and you are running the macro from Sheet1, then you have to go up the hierarchy to make the statement more specific, eg: Sheets(Sheet2).Range(B10).Formula = =B9 * B8 This assumes that you want to enter the formula in cell B10 of the workbook that the macro is being run from (the active workbook). If, however, you wish to enter the formula into cell B10 of Sheet2 of another open work book named, Stock Report, then you have to go up the hierarchy further to make the statement even more specific, eg Workbooks(Stock Report.xls).Sheets(Sheet2).Range(B10).Formula = =B9 * B8
Key Training Solutions Limited Page 55

Introduction to Excel VBA

Lesson 4 Writing Procedures

Think of the Excel Object Model as the organisation chart of your own company or organisation. At the top of the tree is the Managing Director, CEO or Chairperson, etc. If you are very senior, you may work directly for that person (ie. you can be directly controlled by that person) but in most cases, you will be further down the hierarchy controlled by a manger at a lower level. If someone asks you who you work for, you could say that you work for the MD, CEO, or Chair (because ultimately, you do!), but you would normally quote your immediate group or departmental manager. Objects are, therefore, like levels of management, always refer to the one at the lowest possible level. Think of it as always using the lowest common denominator. Examples of common properties that can also be referred to as objects are: Property(Object) Refers to ActiveWorkbook The workbook from which the macro is being run. The sheet from which the macro is being run Examples ActiveWorkbook.Save ActiveWorkBook.PrintOut ActiveWorkbook.Close variable = ActiveWorkbook.FullName ActiveSheet ActiveSheet.PrintOut ActiveSheet.Delete ActiveSheet.PageSetup.Orientation = xlLandscape variable = ActiveSheet.Item ActiveCell The cell that is currently selected ActiveCell.HorizontalAlignment = xlCenter ActiveCell.RowHeight = 20 ActiveCell.EntireColumn.Autofit variable = ActiveCell.Address

SELECTION OR ACTIVECELL?
Discussion
The macro recorder is very fond of using Selection when ActiveCell would be more appropriate, for example: Range("D5").Select Selection.Font.Bold = True In the above case, using Selection has no detrimental effect but it is important to understand the difference between ActiveCell and Selection.
Key Training Solutions Limited Page 56

Introduction to Excel VBA

Lesson 4 Writing Procedures

ActiveCell refers to one specific cell that has been selected or activated. Selection is more appropriate when several cells have been selected. For example: Range("D5").Select ActiveCell.Font.Bold = True but Range("D5:E10").Select Selection.Font.Bold = True If the above piece of code had stated: Range("D5:E10").Select ActiveCell.Font.Bold = True ... only the cell D5 (the one in the top left of the selected area) would be made bold. Selection can refer to many groups (classes) of object, not just cells (range). In the code below, all the charts on a sheet are selected and then deleted. ActiveSheet.ChartObjects.Select Selection.Delete The following example counts the number of drawn objects (shapes) on the sheet, and stores them in a variable named counter. ActiveSheet.Shapes.SelectAll counter = Selection.Count The following example selects all the cells on the sheet and removes all the formatting, leaving just the plain cell contents. Cells.Select Selection.ClearFormats

Key Training Solutions Limited

Page 57

Introduction to Excel VBA

Lesson 4 Writing Procedures

WRITING VBA SUB PROCEDURES


Discussion
Once you have an idea about the basic structure of VBA (concepts of objects, methods and properties) and you learned and become familiar with some commonly used VBA words (by using the macro recorder, looking at examples or reading this manual), you can start to put it all together in a sub procedure of your own. The definition of a sub procedures is a set of instructions that can be performed as a unit. (Those of you who remember DOS, can think of it as a Batch-file, ie. a list of commands to be executed after one another). Creating a sub procedure is like planning a project. You have an objective and you list the necessary sequential steps to achieve it. Once you have identified the file to store the macro in (see page 22) and inserted or found a suitable module sheet onto which to write the code (see page 24), you can start.

a) Sub End Sub


The first word of a sub procedure is Sub. Sub stands for sub procedure and is followed by a name. The name must contain no spaces and punctuation marks are also best avoided, although the underscore may be used to represent spaces. The name should be reasonably descriptive of the purpose of the sub procedure, eg: . Sub SetUpNewReport or Sub Set_up_new_report Capitalisation is unimportant, but if the sub procedure name consists of more than one word (as in the first example above), capitalising the first letter of each word makes it clearer to read and understand what the macro does. Upon pressing enter, the VB Editor will add brackets at the end of the Sub statement, and a new statement a couple of lines below - End Sub. Eg: Sub SetUpNewReport () End Sub The brackets are used for passing arguments to a sub procedure from a called sub procedure, a topic that is outside the scope in this course. In most cases the brackets are left empty. End Sub indicates where the sub procedure ends and must, obviously, be kept as the final line of the sub procedure.
Key Training Solutions Limited Page 58

Introduction to Excel VBA

Lesson 4 Writing Procedures

The VB Editor formats the words, Sub and End Sub with a blue font. This is to highlight them as Key Words - main instructions of the VBA language - rather than an object, method or property.

b) Statements
In between Sub and End Sub, come statements. Statements are the sentences that make up the bulk of each sub procedure. Most (but not all) statements carry out an action on an object by applying methods to it or by altering its properties. The number of statements (and other code) that can be written between Sub and End Sub are too numerous to give here, but examples and principles given earlier in this book should point you in the right direction for writing simple but effective and useful sub procedures. For example, the following add a new sheet to a workbook, moves it to the left of the workbook and then enters and formats a title in cell A1: Sub SetUpNewReport () Sheets.Add Before:= Sheets(1) Range(A1).Value = Stock Report Range(A1).Font.Bold = True Range(A1).Font.Size = 20 Range(A1).Font.Name = Arial Black Range(A1).Font.Color = vbBlue End Sub The following selects all the cells on the active sheet (the one that the macro is being run from) and alters the column widths, row heights and font: Sub FormatAllSheet() Cells.Select Selection.ColumnWidth = 20 Selection.RowHeight = 15 Selection.Font.Name = Calibri Selection.Font.Size = 11 Range(A1).Select End Sub

c) Capitalisation
VBA words always have the first character capitalised. Some VBA words are made up of two or more words (eg. ActiveWorkbook; ActiveCell;

Key Training Solutions Limited

Page 59

Introduction to Excel VBA

Lesson 4 Writing Procedures

ColumnWidth; CommandBarButton) and in these cases, the first character of the second or subsequent word(s) is also capitalised. In practice, it is not necessary to capitalise your VBA words as you type. In fact, it is recommended that you always write in lower case because when you press Enter at the end of a statement or you move off the line, the VB Editor will capitalise for you. This is a good way of ensuring that the words you have written are valid, VBA words. Any word(s) not capitalised are probably typos or variables (see page 87). This does not guarantee, however, that your VBA words will have the desired effect in the context that you have used them!

d) White Space and Indentations


Some developers believe that although formatting code might make it look pretty, it is not really worth the time and effort. Properly formatted code, however, has nothing to do with appearance and everything to do with how easy your code is to understand and maintain. Formatting also helps detail the code by showing the logic and flow of a procedure and by grouping logically related sections of code. Use blank lines to separate logically related blocks of code, introductory (header) comments from the first variable declaration, and the last declared variable from the code itself. Indent code and comments within a procedure by using a two- to four-space tab stop. (The Visual Basic Editor uses a four-space tab stop by default.) As with white space, indents are used to organize code logically and make it visually appealing. Concern is often expressed over whether one should add spacing between statements or indent them. To put it simply, you dont have to add any spacing or indentations at all. They have no effect on the way that the code is executed and are added purely for neatness and clarity. Indenting statements will be elaborated further in some subsequent lessons and topics.

e) Comments
It is always a good idea to add notes to a sub procedure, not only to describe and/or remind yourself what is happening or why, but also for the benefit of other people who may have to edit your code in the future. Comments are added simply by preceding them with an apostrophe (). A comment can be added on a line of its own, eg: The following code formats the range with a currency style Range(B16:F16).Style = Currency Or, it can be added at the end of a statement, eg: Range(B16).Formula = =SUM(B3:B15) Adds up the column B figures

Key Training Solutions Limited

Page 60

Introduction to Excel VBA

Lesson 4 Writing Procedures

The VB Editor formats comments in green to make them stand out more clearly. Precede all comments with a blank line

f) Line Breaks
Some statements can be very long, especially where many arguments are being used with a method, or your code is entering a long text string into a cell. This results in part of the code extedning off the right edge of the screen and making it difficult to read without scrolling. Unlike normal word-processing where a line break can normally be created by pressing Enter, it is not so straightforward in the VB Editor. Before you press Enter to break a statement, you must type a line-continuation character an underscore (_) preceded by a space. The line-continuation character cannot be added just anywhere, it has to be added where there is a natural gap in the statement, ie. not in between a single word (eg. Range, xlDescending, False) or inside special characters (eg. :=) Consider the following long statement that sorts a table of data (range A1:F12) by column A in a descending order. Range("A1:F12").Sort Key1:=Columns("A"), Order1:=xlDescending, Header:=xlGuess, MatchCase:=False Line breaks could be added as follows: Range("A1:F12").Sort Key1:=Columns("A"), Order1:=xlDescending, _ Header:=xlGuess, MatchCase:=False or: Range("A1:F12").Sort Key1:=Columns("A"), _ Order1:=xlDescending, Header:=xlGuess, _ MatchCase:=False But NOT: Range("A1:F12").Sort Key1:=Colu _ mns("A"), Order1:=xlDescending, Header:=xl _ Guess, MatchCase:=False In fact, if you attempted to write the above example, you would receive the following message.

Key Training Solutions Limited

Page 61

Introduction to Excel VBA

Lesson 4 Writing Procedures

In the case of long text strings, line breaks need to have added an ampersand concatenation character (&) placed at the beginning of the continuation line as follows: . Range(B2).Value = Fourscore and seven years ago our fathers " _ & "brought forth, on this continent, a new nation, " _ & "conceived in liberty, and dedicated to the " _ & "proposition that all men are created equal."

THE WITH ... END WITH BLOCK


Discussion
There are several types of statement in VBA that come in blocks. Block statements are characterised by having sub-statements written within them that the block carries out special actions on. Examples of statements that come in blocks are the If statement and loops. These will be covered in more detail later in this book (see pages 87, 81 & 96). A useful general-purpose block is the With ... End With block. This allows you to perform a series of statements on a specified object (and/or associated property) without having to retype it repeatedly. Not can this improve performance, but also reduces the risk of typos. Think of a With block a bit like using ditto in normal written communications. Consider the following code that enters and formats a title into cell A1: Sub AddReportTitle () Range(A1).Value = Stock Report Range(A1).Font.Bold = True Range(A1).Font.Size = 20 Range(A1).Font.Name = Arial Black Range(A1).Font.Color = vbBlue End Sub

Key Training Solutions Limited

Page 62

Introduction to Excel VBA

Lesson 4 Writing Procedures

Note how by using a With ... End With block, repetitive typing of Range(A1) is avoided: . Sub SetUpNewReport () With Range(A1) .Value = Stock Report .Font.Bold = True .Font.Size = 20 .Font.Name = Arial Black .Font.Color = vbBlue End With End Sub By using a nested With ... End With block inside the first one, repetitive typing of .Font can also be avoided: Sub SetUpNewReport () With Range(A1) .Value = Stock Report With .Font .Bold = True .Size = 20 .Name = Arial Black .Color = vbBlue End With End With End Sub

THE OFFSET FUNCTION


Discussion
VBA offers several different ways to refer to ranges: Referring to ranges directly (eg. Range(A1) , Range(B10:F10) , etc.) Referring to ranges by using the Cells method (eg. Cells(1) , Cells (2 , 2) , etc.) Referring to ranges by using the Offset property

The first two methods have already been described in previous lessons (see page 49).
Key Training Solutions Limited Page 63

Introduction to Excel VBA

Lesson 4 Writing Procedures

The best way of describing using the Offset property is to think of it as a way of referring to a cell that is away from another cell by a certain number of rows and columns. Although Offset is a property and properties are normally equal to something, Offset takes an argument in brackets as follows: Offset(rowoffset , columnoffset) RowOffset is the number of rows away from the object that you want to refer. Positive values are offset downward, and negative values are offset upward. ColumnOffset is the number of columns away from the object that you want to refer. Positive values are offset to the right, and negative values are offset to the left.

Offset(-1 , 0) Up one row, same column Offset(0 , -1) Same row, left one column Cell being referred to Offset(1 , 0) Down one row, same column Offset(0 , 1) Same row, right one column

The following example puts a value of 100 to the cell that is one row below cell C2 and two cells to the right of C2 (ie. cell E3): . Range("C2").Offset(1 , 2).Value = 100

An advantage of the Offset function in VBA is that you can do things to a cell away from the one that is currently active without having to select it. Not only does this create more concise code, but it can significantly speed up its execution. The following code enters random numbers between 1 and 50 into the active cell and all the cells surrounding it without actually selecting them.

Key Training Solutions Limited

Page 64

Introduction to Excel VBA

Lesson 4 Writing Procedures

Sub EnterRandomNumbers With ActiveCell .Value = Rnd * 50 .Offset(-1 , 0).Value = Rnd * 50 .Offset(0 , 1).Value = Rnd * 50 .Offset(1 , 0).Value = Rnd * 50 .Offset(0 , -1).Value = Rnd * 50 End With End Sub

DEALING WITH A RUNTIME ERROR


Discussion
In many cases, the VB Editor is able to alert you to certain errors in your statements as you write them. When you press enter, the VB Editor checks your code and if there is something its not happy with, it will show a Compile error message and highlight the faulty code in red. Some of these are shown below and they can often be rather vague as to their meaning.

Some errors, however, cannot be identified until you actually run the sub procedure. These usually (but not always) show up as Run-time errors and are characterised by the following message window:

A Run-time error message The window is essentially telling you that the sub procedure had to stop at a certain point, because it encountered an unexpected condition. The Run-time error number
Key Training Solutions Limited Page 65

Introduction to Excel VBA

Lesson 4 Writing Procedures

can, under certain circumstances, help you identify the problem and is an essential tool is writing error trapping code into your sub procedure. This, however, is outside the scope of this particular course. In some cases, the Run-time error occurs at the very start of the sub procedure and no statements are executed. In other cases where the Run-time error has occurred in the middle or near the end of the sub procedure, some actions will have been carried out before it came to a stop without completing through got the end. You have several options on how to deal with a Run-time error message: a) Click Help to read about the problem b) Click End to terminate the sub procedure c) Click Debug to take you to the VB Editor and to the statement where the error occurred. The statement will be highlighted in yellow (called Step Mode). If you understand what the error is and can fix it, you should then click the Continue button on the toolbar of the VB Editor in order for the sub procedure to attempt the statement again and, hopefully, complete through to the end. If you are unable to deal with the error, you should click the Reset button on the toolbar of the VB Editor in order to exit the sub procedure. You should then consult the person who wrote the macro and seek their advice and co-operation is resolving the problem. In the case of a run-time error, you must click either the Continue of the Reset button. If you do not you will be unable to run any other macros. Clicking the End button in the Run-time error window is equivalent to resetting the macro.

VB Editor showing Step Mode following a Run-time error

Key Training Solutions Limited

Page 66

Introduction to Excel VBA

Lesson 4 Writing Procedures

Procedures
1. Click the Debug button window. in the Run-time error

2. Edit the highlighted code, if possible. 3. Click the Continue button been successfully edited. if you believe that the error has

button if the error has not been Click the Reset successfully edited. 4. Close the VB Editor or switch back to the Excel window.

USING THE OBJECT BROWSER


Discussion
The VB Editor provides you with a tool for identifying Excel objects and seeing which methods and properties can be associated with them. This is called the Object Browser and can be displayed over the code window; it makes a useful learning tool and point of reference for both VBA novices and seasoned developers.

The VB Editor with the Object Browser displayed

Procedures
1. Launch the VB Editor.

Key Training Solutions Limited

Page 67

Introduction to Excel VBA

Lesson 4 Writing Procedures

108.

Click the Object Browser button

on the toolbar.

109. Click the drop down list in the top left corner of the Object Browser.

110. 111.

Select Excel. View the left-hand pane to identify Excel Objects (Classes)

112. Right-click an object and select Help from the menu to learn more about it. 113. Select an object in the left-hand pane. and properties in

114. View its associated methods the right-hand pane.

115. Right-click a method or property and select Help to learn more about it. 116. Double click a module or Excel object in the Project Explorer pane to close the Object Browser.

Key Training Solutions Limited

Page 68

Introduction to Excel VBA

Lesson 4 Writing Procedures

EXERCISE
WRITING SUB PROCEDURES
1. Launch the VB Editor. 2. Insert a module into the Personal Macro Workbook (personal.xls). 3. Create a new sub procedure named, OpenAndFormat.

4. Enter into the sub procedure a comment stating: This macro opens the Regional Sales workbook and formats the headings on the first sheet.

5. Type the first statement for the sub procedure into the module sheet. The statement must open the workbook named Regional Sales.xls from the train folder on the c:\ drive.

6. The next statement must activate the first sheet at the left of the workbook.

7. The next statement must select cell A1 on the active sheet.

Key Training Solutions Limited

Page 69

Introduction to Excel VBA

Lesson 4 Writing Procedures

8. The next group of statements must format the active cell with: A font size of 18 A font name of Arial Black A font colour of Blue

9. The next statement must change the column width of the active cell to 20.

10. The next statement must select cell A3.

11. The next statement must insert an entire row where the active cell is.

12. The next statement must select the range A4 to H4.

13. The next statement must format the selected range with: A bold font A cyan interior colour

14. The final statement of the sub procedure must select cell A1

Key Training Solutions Limited

Page 70

Introduction to Excel VBA

Lesson 4 Writing Procedures

15. The completed sub procedure should be:

16. The sub procedure should produce the following result:

17. Save the Regional Sales workbook then exit Excel and save the Personal Macro Workbook, if prompted.

Key Training Solutions Limited

Page 71

LESSON 5 CONTROL STRUCTURES


In this lesson, you will learn how to:
Create decision-making code using the If control structure Create decision-making code using the Select Case control structure Repeat code using Do loops

Introduction to Excel VBA

Lesson 5 Control Structures

THE IF-THEN CONTROL STRUCTURE


Discussion
The If-Then control structure enables you to carry out a test and change the actions that a macro performs, based on whether the test is true or is false. The test in an If-Then control structure usually contains at least one conditional statement. Conditional statements involve the use of comparison operators. A list of these is given below: Symbol = > >= < <= <> Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to Operator

Examples of simple If-Then control structures are as follows: 1. Single Line form. If <test> Then <action if true> If the test is false, nothing specific will happen and any following code is NOT dependant on the test. For example: If Range(A3).Value >= 100 Then Range(A3).Font.Bold = True In the single line form, multiple actions can be performed but the code becomes long and complex to read. A colon (:) must be used to separate the actions, the syntax is as follows: If <test> Then <action1 if true> : <action2 if true> : etc... 2. Block Form This syntax is more flexible and clearer to read when there are multiple actions to perform if the test is true. If the test is false, nothing happens. Note the use of End

Key Training Solutions Limited

Page 73

Introduction to Excel VBA

Lesson 5 Control Structures

If to close off the control structure. Any code following the End If is NOT dependant on the test being true. If <test> Then <actions if true> End If For example: If Range(A3).Value > 100 Then Range(A3).Font.Bold = True Range(A3).Font.Size = 14 Range(A3).Font.Color = vbBlue End If Although, you can use the single-line form for short, simple tests. However, the block form provides more structure and flexibility than the single-line form. Using block form makes it easier to read, maintain, and test. Other examples of tests that might be used as tests in an If-Then control structure are: If ActiveCell.Value = Bonus Then <action if true> (If the active cell equals the word bonus, then...) If Range(C10).Value >= 100 Then <action if true> (If cell C10 contains a value greater than or equal to 100, then...) If ActiveCell <> Then <action if true> (If the active cell is not empty (contains no text), then...) If ActiveCell.Offset(0, 1).Value > 100 Then <action if true> (If the cell on the same row and one column to the right of the active cell is greater than 100, then...) If Range(A6).Font.Bold = TRUE Then <action if true> (If cell A6 contains bold font, then...
Indentations to the actions if true code is added purely for clarity and to give structure to the block.

Key Training Solutions Limited

Page 74

Introduction to Excel VBA

Lesson 5 Control Structures

A test can be elaborated further by adding And and/or Or conditions to it. The syntax is as follows: If <test1> And <test2> And <test3> Then <actions if true> End If In the above example, test1, test2 and test3 must ALL be true for the actions if true to occur. If even one of the tests is false, the If ends without carrying out any actions. In the following example only ONE of the test needs to be true in order for the actions if true to occur. If <test1> Or <test2> Or <test3> Then <actions if true> End If And and Or can also be mixed together, for example: If <test1> And <test2> Or <test3> Then <actions if true> End If

Procedures
1. Position the cursor in the macro where you want to place the statement. 2. Type If. 3. Type a space. 4. Type a valid test. 5. Type a space. 6. Type Then. 7. Press Enter. 8. Type the statements that you want the macro to perform if the test is true. 9. Press Enter. 10. Type End If. 11. Add additional code as necessary.

Key Training Solutions Limited

Page 75

Introduction to Excel VBA

Lesson 5 Control Structures

THE IF-THEN-ELSE CONTROL STRUCTURE


Discussion
As discussed in the previous topic, the If-Then control structure carries out actions only if the test(s) is/are true. In cases where there is a need for separate actions to be performed if the test is false, the If-Then-Else control structure can be used. The single-line form of the If - Then - Else control structure is: If <test> Then <actions if true> Else <actions if false> Any code following this will be executed irrespective of whether the test is true or false. Because the single-line form can become very long and difficult to read, the block form is preferable in almost all cases: If <test> Then <actions if true> Else <actions if false> End If Any code following the End If will be executed irrespective of whether the test is true or false.

Procedures
1. Position the cursor in the sub procedure where you want to place the statement. 2. Type If. 3. Type a space. 4. Type a valid test. 5. Type a space. 6. Type Then. 7. Press Enter. 8. Type the statements that you want the sub procedure to perform if the test is true.

Key Training Solutions Limited

Page 76

Introduction to Excel VBA

Lesson 5 Control Structures

9. Press Enter. 10. Type Else. 11. Type the statements that you want the sub procedure to perform if the test is false. 12. Press Enter. 13. Type End If. 14. Add additional code as necessary.

USING ELSEIF IN A CONTROL STRUCTURE


Discussion
As discussed in the previous topic, the If - Then - Else control structure carries out one set of actions if the test is true, and another if the test is false. By using And and/or Or, you can make the test carry out multiple simultaneous tests. What, however, if you want to carry out multiple sequential tests? In this case ElseIf needs to be incorporated into the If control structure. The syntax is as follows: If <test1> Then <actions if true> ElseIf <test2> Then <actions if true> Else <actions if false> End If In the example below, the font in the active cell is made blue if it contains a value of Status A. If, however, the active cell does not contain Status A, control is passed to the ElseIf, which carries out a second test to establish if it contains the value Status B. If this is true then the font in the active cell is made green. If the active cell does not contain Status B either, then control passes to Else and under all other circumstances makes the font red.

Key Training Solutions Limited

Page 77

Introduction to Excel VBA

Lesson 5 Control Structures

If ActiveCell.Value = Status A Then ActiveCell.Font.Color = vbBlue ElseIf ActiveCell.Value = Status B Then ActiveCell.Font.Color = vbGreen Else ActiveCell.Font.Color = vbRed End If ElseIf cannot be used in the single-line form. There is no limit to how many ElseIfs are added to the block. Rules for If - Then - ElseIf - Then - Else control structures The first test in the block must always be preceded by If; Subsequent tests must be preceded by ElseIf; Else always comes last in the block to cover any possibilities that have not been eliminated by previous tests. All test whether the initial If or subsequent ElseIfs must be followed by Then.

Procedures
1. Position the cursor in the sub procedure code where you want to place the statement. 2. Type If. 3. Type a space. 4. Type a valid test. 5. Type a space. 6. Type Then. 7. Press Enter. 8. Type the statements that you want the sub procedure to perform if the test is true. 9. Press Enter. 10. Type ElseIf. 11. Type a space. 12. Type a valid test. 13. Type a space. 14. Type Then. 15. Press Enter.
Key Training Solutions Limited Page 78

Introduction to Excel VBA

Lesson 5 Control Structures

16. Type the statements that you want the sub procedure to perform if the test is true. 17. Press Enter. 18. Type Else. 19. Type the statements that you want the sub procedure to perform if the test is false. 20. Press Enter. 21. Type End If. 22. Add additional code as necessary.

THE SELECT CASE CONTROL STRUCTURE


Discussion
Select Case can be used as an alternative to If - Then - ElseIf - Else where several conditions may need to be evaluated. This often seen as a more efficient, clearer to read and more concise way of coding where multiple conditions need to be evaluated. It does, however, lack the flexibility and power of If - Then - ElseIf - Else where each condition can involve different variables. The syntax of the Select Case control structure is: Select Case <expression> Case Is = <value1> <actions if true> Case Is = <value2> <actions if true> Case Else <actions under all other circumstances> End Select A single expression is evaluated at the top of the Case structure. Each case is then checked for this value, and the appropriate statements executed. Control is then passed to the statement after the End Select statement. If no Case statement holds the evaluated value, then the statements after the Case Else are executed. Case Else is optional. In the example below, the font in the active cell is made blue if it contains a value of Status A

Key Training Solutions Limited

Page 79

Introduction to Excel VBA

Lesson 5 Control Structures

If, however, the active cell does not contain Status A, control passes to the second Case Is and if the active cell contains the value Status B, the font in the active cell is made green. If the active cell does not contain Status B either, then control passes to the Case Else and under all other circumstances makes the font red. Select Case ActiveCell.Value Case Is = Status A Activecell.Font.Color = vbBlue Case Is = Status B Activecell.Font.Color = vbGreen Case Else Activecell.Font.Color = vbRed End Select The usual comparison operators can be used after the Case Is, such as: Case Is > <value> Case Is >= <value> Case Is < <value> Case Is <= <value> Case Is <> <value>

Procedures
1. Position the cursor in the sub procedure code where you want to place the statement. 2. Type Select Case. 3. Type a space. 4. Type the object.property that you want to carry out tests on. Eg. ActiveCell.Value 5. Press Enter. 6. Type Case Is. 7. Type a valid comparison operator, eg. = or > or < or >= or <= or <>. 8. Type the value that you want to compare the object/property against. 9. Press Enter.

Key Training Solutions Limited

Page 80

Introduction to Excel VBA

Lesson 5 Control Structures

10. Type the statements that you want the sub procedure to perform if the test is true. 11. Press Enter. 12. Add further Case Is <comparison operator> <value> statements, if necessary. 13. At the end of the Case Is statements, type Case Else if there is a final set of actions that you want the sub procedure to perform if none of the previous tests are true. 14. Press Enter. 15. Type End Select. 16. Add additional code as necessary.

USING A DO LOOP STATEMENT


Discussion
Loops are used to run the same statements a certain number of times. Loops can be constructed in many ways to suit different circumstances and often, the same result can be obtained by using different loops. There are two main types of loops DO loops and FOR loops. DO loops keep repeating statements while a condition exists or until a condition is met (eg. do this until you get to row 100, or do this while there is data in a cell). FOR loops repeat statements a fixed number of times (eg. do this 10 times), or as a variable (eg. do this for as many times as there are cells in a selected range). The basic structure of all loops is the same, ie. 1. Start of Loop (tells the sub procedure how often to repeat the statement(s) that follow(s)) 2. Statements (the actions to perform a certain number of times) 3. End of Loop (tells the sub procedure to return to the start of the loop and check whether it has carried out the statements a sufficient number of times) In this lesson, the DO loop is examined. FOR loops are discussed and demonstrated separately on page 96. A DoLoop is used to run a block of statements until a condition is True or while a condition becomes True. It comes in two forms Do Until and Do While. In the
Key Training Solutions Limited Page 81

Introduction to Excel VBA

Lesson 5 Control Structures

example below, cells in a column (starting at the top of the column) are formatted bold until an empty one is reached. Do Until ActiveCell.Value = (Do the following statements until the active cell is empty) ActiveCell.Font.Bold = True (Make bold the font of the active cell) ActiveCell.Offset(1,0).Select (From the active cell, move down 1 row, same column) Loop (Return to Do Until and check if the active cell is empty. If TRUE, repeat the statement; if FALSE continue the sub procedure from after Loop.) In the same example, a Do While loop would look like this: Do While ActiveCell.Value <> (Do the following statements while the active cell is not empty) ActiveCell.Font.Bold = True (Make bold the font of the active cell) ActiveCell.Offset(1,0).Select (From the active cell, move down 1 row, same column) Loop (Return to Do While and check if the active cell is not empty. If TRUE, repeat the statement; if FALSE continue the sub procedure from after Loop.) It is important to check the condition before entering a loop. If the condition is FALSE the contents of the loop will never execute. In cases where this is an issue, use the following to ensure that the statements are executed at least once: Do (Do the following statements) ActiveCell.Font.Bold = True (Make bold the font of the active cell) ActiveCell.Offset(1,0).Select (From the active cell, move down 1 row, same column) Loop Until ActiveCell = (Check if the active cell is empty. If TRUE, return to Do and repeat the statements; if FALSE continue the sub procedure from after Loop Until...)
Key Training Solutions Limited Page 82

Introduction to Excel VBA

Lesson 5 Control Structures

Or... Do (Do the following statements) ActiveCell.Font.Bold = True (Make bold the font of the active cell) ActiveCell.Offset(1,0).Select (From the active cell, move down 1 row, same column) Loop While ActiveCell <> (Check if the active cell is not empty. If TRUE, return to Do and repeat the statement; if FALSE continue the sub procedure below Loop While...) The Not operator can be used in a Do loop to reverse the logic of the condition. The syntax would be, for example: Do Until Not ActiveCell.Value = Statement(s) Loop This would be the same as: Do Until ActiveCell <> Statement(s) Loop To stop an endless loop press Esc or Ctrl + Break.

More Do loop examples: 1. Move down a column of data until an empty cell is found: Do While ActiveCell.Value <> ActiveCell.Offset(1,0).Select Loop

Key Training Solutions Limited

Page 83

Introduction to Excel VBA

Lesson 5 Control Structures

2. Move across a row of data until the cell is found containing todays date: Do Until ActiveCell.Value = Date (Date is a VBA function that returns the current date from the system clock. Equivalent to the =TODAY() Excel worksheet function)

ActiveCell.Offset(0,1).Select Loop 3. Move down a column of data until you get to a cell containing bold font. Add a blue font colour to cells with a value higher than 100. Do Until ActiveCell.Font.Bold = TRUE If ActiveCell.Value > 100 then ActiveCell.Font.Color = vbBlue End If ActiveCell.Offset(1,0).Select Loop

Procedures
1. Position the cursor in the sub procedure code where you want to place the statement. 2. Type Do Until or Do While. 3. Type a space. 4. Type the condition for the Until or While, 5. eg. ActiveCell.Value = or ActiveCell.Offset(0,1) <> 6. Press Enter. 7. Type the statements that you want the sub procedure to perform until or while the condition is true. 8. Press Enter. 9. Type Loop. 10. Add additional code as necessary.

Key Training Solutions Limited

Page 84

Introduction to Excel VBA

Lesson 5 Control Structures

EXERCISE
DECISIONS-MAKING CODE AND DO LOOPS
1. Open the file Practice Decision. 2. Insert a module sheet to the workbook and write a sub procedure named, CheckStock which uses an IF statement block to check the value of an active cell and if the value is less than 300 enters Order now into the cell to the right. 3. Place a DO loop around the IF statement so that it runs down a column until it comes to an empty cell. 4. On the Inventory sheet, select cell C5 and run the CheckStock sub procedure. 5. Edit the sub procedure so that in cases where the value is not less than 300, the text, "Hold Order" is entered into the cell to the right. 6. Delete the text in cells D5:D10 and run the CheckStock procedure again to test your code. 7. Finally, edit your procedure again so that if the cell being tested is equal to 0, the words, "Out of stock" is entered into the cell to the right and formatted to RED font. 8. Run to test the procedure again. 9. Save and close the file. 10. Open the file Personnel Record. 11. Write a procedure named BonusAward and use a CASE SELECT statement block and a DO statement block to carry out the following actions on the table: Test length of service is greater than 5 years length of service is greater than 10 years length of service is greater than 20 years Enter in Bonus column 2% 3% 5%

12. Test the procedure on the values in column D.

Key Training Solutions Limited

Page 85

LESSON 6 DATA VARIABLES


In this lesson, you will learn how to:
Create data variables and learn how to assign values to them Declare variables

Introduction to Excel VBA

Lesson 6 Data Variables

DATA VARIABLES
Discussion
Data variables are used to hold information temporarily whilst a sub procedure is running; information that can be used later in the sub procedure to carry out a calculation or make a decision. In some cases, the information stored in the variable can be returned to an Excel workbook to achieve a result or carry out an action. One way of thinking of a variable is to look at it as being a container into which you can put something. This something can be many things, eg: A text string A number A date An object (although this is not covered on this course)

Variables can also help make your sub procedures more interactive. Consider the following statement that opens an Excel file: WorkBooks.Open (Sales Data.xls) (Open the Excel file named Sales Data) Now consider the following where cell A1 contains the text, Sales Data.xls: fileTo Use = Range(A1).Value (This creates a variable named fileToUse and stores in it the text, Sales Data) WorkBooks.Open (fileToUse) (This uses the text stored in the variable, fileToOpen, to open the workbook) The second example provides more flexibility because it is easier to change the contents in cells A1 with the name of the file that you want to open, than accessing the module and changing the code in the sub procedure.

CREATING VARIABLES AND ASSIGNING VALUES


Discussion
To create a variable, you invent a word to use as a name for the variable and then make it equal to something. Rules for creating variable names include: . Single characters (eg. a, b, c, x, y, z) should be avoided unless the variable if being used for simple counting purposes. Using this type of variable name can
Page 87

Key Training Solutions Limited

Introduction to Excel VBA

Lesson 6 Data Variables

cause ambiguity and it is better to use descriptive, but concise, names for your variables, eg: newname, salesfig, startdate, numcells. A variable name must start with a letter and not a number. Numbers can be included within the name, but not as the first character, eg. salesfig1 but not 1salesfig. The first character of a variable name should be left lowercase. Because VBA words always start with an uppercase character (eg. ActiveCell, WorkBook, Cells), keeping the first character lowercase helps make your variables stand out more clearly in the sub procedure. Avoid using names that conflict with VBA words such as: activecell, sheets, font, cells, etc. Spaces cannot be used in variable names. You can separate words by either capitalisation, eg. newName, or by using the underscore character, eg. new_name. Most punctuation marks (eg. , . : ; ? -) and special characters (eg. $, %, ^, &, #, }) cannot be used. A variable name can be no longer than 250 characters.

1.

Assigning a value to a data variable can be done by: Assigning a value from a cell on a worksheet. celVal = Range(A1).Value Assigns the value in cell A1 of the active sheet to the variable celVal. celVal would, therefore, be a piece of text (a string) or a number. If cell A1 were empty, then celVal would store an empty string (viz. nothing!). myNum = Cells(3,4).Value Assigns the value in cell that is at the intersection of row 3 and column 4 of the active sheet(ie. D4) to the variable myNum. myNum would, therefore, be a piece of text (a string) or a number. If cell D4 was empty, then myNum would store an empty string. 2. Giving the variable a value, either within the sub procedure or via user interaction (eg. by means of an input box, see page 112). firstNum = 10 secNum = 20 thirdNum = firstNum * secNum MsgBox thirdNum. Stores the number 10 in the variable firstNum; stores the number 20 in the variable secNum and stores their product in the variable thirdNum. Displays the variable thirdNum in a message box.

Key Training Solutions Limited

Page 88

Introduction to Excel VBA

Lesson 6 Data Variables

fileToUse = InputBox(Enter the name of the file to open) WorkBooks.Open (fileToUse)

Prompts the user to type a file name and then opens it.

3.

Assigning a value by means of a test carried out on an object property. isItBold = ActiveCell.Font.Bold. Stores in the variable isItBold a TRUE or a FALSE based on whether the font in the active cell is bold or not. Stores in the varable numCells a number denoting the number of cells in a selected range. Stores in the variable celAddr the absolute reference of the cell that is at the intersection of row 3 and column 4 (ie. $D$4).

numCells = Selection.Cells.Count

celAddr = Cells(3,4).Address

Variables can change their values during the execution of a sub procedure. The following example uses the value of the variable tempVal in a calculation, and then changes it to a different value for a second calculation. tempVal = 0.15 calc1 = ActiveCell.Value * tempVal tempVal = 0.22 calc2 = ActiveCell.Value * tempVal Another example of changing the value of a variable is for counting the number of times that a condition is encountered, or where there is a need to count the number of times that a loop has executed. The following example uses a variable, numBold to count the number of cells in a column containing bold font. It then returns the value of counter into cell A1.

Key Training Solutions Limited

Page 89

Introduction to Excel VBA

Lesson 6 Data Variables

counter = 0 (Create a variable named counter and store in it a zero) Do Until ActiveCell.Value = (Do the following statements until the active cell is empty) If ActiveCell.Font.Bold = True Then (If the active cell contains bold font then...) counter = counter + 1 (Increase the value of counter by 1 (ie. make the new value of counter its old value + 1)) End if ActiveCell.Offset(1,0).Select (From the active cell, move down 1 row, same column) Loop (Return to Do Until and check if the active cell is empty. If FALSE, repeat the statement; if TRUE continue the sub procedure from after Loop.) Range(A1).Value = counter (Return to cell A1 the value of counter)

Procedures
1. Position the cursor in the sub procedure code where you want to create the variable. 2. Type a name for the data variable keeping in mind the naming rules. 3. Type =. 4. Type a value for the variable; this can be a number, a string, a boolean expression (True or False) or an object/property that returns one of the above values, 5. eg. ActiveWorkBook.Name or ActiveCell.Value 6. Press Enter. 7. Add additional code as necessary. The following example, uses two counters. One to count the number of cells containing bold font (counter1) and the second to count the number of times that the loop has executed (counter2). Counter2, therefore, counts the number of cells that have been checked in the column.

Key Training Solutions Limited

Page 90

Introduction to Excel VBA

Lesson 6 Data Variables

counter1 = 0 counter2 = 0 (Create variables named counter1 and counter2 and store in them zero) Do Until ActiveCell.Value = (Do the following statements until the active cell is empty) If ActiveCell.Font.Bold = True Then (If the active cell contains bold font then...) Counter1 = counter1 + 1 (Increase the value of counter1 by 1 (ie. make the new value of counter its old value + 1)) End if ActiveCell.Offset(1,0).Select (From the active cell, move down 1 row, same column) counter2 = counter2 + 1 (Increase the value of counter2 by 1. Because this statement will occur each time the loop is repeated irrespective of whether the IF is true or false, it will count the total number if times that the loop has executed) Loop (Return to Do Until and check if the active cell is empty. If FALSE, repeat the statement; if TRUE continue the sub procedure from after Loop.) Range(A1).Value = counter1 Range(A2).Value = counter2 (Return to cell A1 the value of counter1 the number of cells containing bold font and return to cell A2 the value of counter2 the number of cells checked)

VARIABLE TYPES
Discussion
It was mentioned previously that variables can store many things (see page 87). It is, therefore, good practice (although not always necessary in VBA) to tell the sub procedure in advance, what variables are going to be used and the type of data that is going to be stored in them. By doing this, you are not only helping to prevent potential errors and ambiguity in the sub procedure, but also improving the efficiency and performance of the sub procedure by assigning an appropriate amount of computer memory for storing the variable. Although this will have relatively little impact on a small sub procedure that uses just a few variable, it could slow down or crash the computer in cases where there are hundreds of lines of code using dozens of variables. The process of doing this is called declaring a variable, .and is usually carried out at the beginning of a sub procedure by using a Dim statement as follows: .
Key Training Solutions Limited Page 91

Introduction to Excel VBA

Lesson 6 Data Variables

Dim <variable name> As <type> Unless otherwise specified, undeclared variables are assigned the Variant data type. If a data type is not specified, eg. Dim <variable name> ... the variable will default to a variant data type. This data type makes it easy to write sub procedures, but it is not always the most efficient data type to use. Because the sub procedure does not know what you are going to put into a variant variable, it may create an unnecessarily large space in the computers memory with a resulting loss of performance. You should consider using appropriate data types if: Your program is very large and uses many variables. Your program must run as quickly as possible. You write data directly to random-access files.

The following provides a list of the more commonly used variables types for storing data. Data type Byte Boolean Integer Long Single Double Memory size 1 byte 2 bytes 2 bytes 4 bytes 4 bytes 8 bytes Storage capability 0 to 255 True or False -32,768 to 32,767 -2,147,483,648 to 2,147,483,647 -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values -922,337,203,685,477.5808 to 922,337,203,685,477.5807 +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001 January 1, 100 to December 31, 9999 0 to approximately 2 billion

Currency Decimal

8 bytes 14 bytes

Date

8 bytes

String 10 bytes + (variable-length) string length


Key Training Solutions Limited

Page 92

Introduction to Excel VBA

Lesson 6 Data Variables

During a sub procedure, a variable may be assigned different values and data types. The last declaration will determine what the variable is allowed to store. In the following example, the variable myVar is used firstly to store a number, and then to store a date. Dim myVar as Single myVar = 1234.5678 Dim myVar as Date myVar = #01/05/2009# If a specific data type is assigned to a variable, the variable will only be able to hold that type of data. If storing a different data type is attempted, an error message will be displayed when the sub procedure is run.

Procedures
1. Position the cursor on the line below the sub procedure name. 2. Type Dim. 3. Type a space. 4. Type a name for the first variable that you intend using in the sub procedure. 5. Type a space. 6. Type As. 7. Type a space. 8. Type (or select from the members list) the type of data that the variable will store. 9. Press Enter. 10. Add additional code as necessary.

Key Training Solutions Limited

Page 93

Introduction to Excel VBA

Lesson 6 Data Variables

EXERCISE
TO ASSIGN VALUES TO VARIABLES.
1. Open the file, Practice Variables. 2. Create a sub procedure named, VatCalc that: stores the current rate of VAT in a variable named vatRate stores the contents of an active cell in a variable named celAmount returns in the cell to the right of the active cell the amount plus VAT

3. Run the macro on cell B5. If working correctly, a value of 115.00 should be returned into cell C5. 4. Repeat with cells B6 and B7, the results in cells C6 and C7 should be 230.00 and 345.00 respectively. 5. Edit the sub procedure to declare the variables. 6. On Sheet2 on the workbook, use declared variables a necessary to create a sub procedure named TransferNames that will reverse the position of Bill and Ben. 7. Test the macro. If correct, Bill should be moved to cell B1 and Ben moved to cell A1. 8. Repeat the sub procedure. The names should move back to their original positions. 9. Save and close the file.

Key Training Solutions Limited

Page 94

LESSON 7 USING THE FOR LOOP


In this lesson, you will learn how to:
Create and use a For To loop Create and use a For Next loop

Introduction to Excel VBA

Lesson 7 The For Loop

USING A FOR... NEXT LOOP


Discussion
The purpose of loops was discussed on page 81. Special reference was given to the Do loop but there also exists the For loop. There are two forms of the For loop For... Next and For Each... Next. This section looks at the For Next loop. The For Next loop allows a series of statements to be repeated a specific number of times. It needs a container to do the counting in, hence the use of a variable in its syntax. For variable = start To end Step step Statements Next variable The structure repeats the statements a number of times depending on the values of start, end and step. Variable is a made-up name (naming rules apply see page 87), which holds a number, the variable name is set to equal start, and each time the statements are run, the variable name increments by the value of step. If step is omitted then, the increment will default to one. For example, the following loops through the statement 6 times, creating random numbers between 1 and 49 in a column. Dim counter as Byte For counter = 1 To 6 ActiveCell.Value = Rnd * 49 (Rnd is a VBA function that returns a value less than 1 but greater than or equal to zero. It is equivalent to the =RAND() Excel worksheet function.)

ActiveCell.Offset(1,0).Select Next counter The following examples uses a variable (numCells) to count the number of cells in a selected range (a column). It then starts with the first cell in the range (ActiveCell) and loops through the statements as many times as there are cells in the range, doubling their value.

Key Training Solutions Limited

Page 96

Introduction to Excel VBA

Lesson 7 The For Loop

Dim numCells as Integer Dim counter as Integer numCells = Selection.Cells.Count For counter = 1 To numCells ActiveCell.Value = ActiveCell.Value * 2 Next counter The real power of the For... Next loop comes by using the value of the variable within the loop. The following example shows code that loops 100 times (1 To 100). The first time round the loop, the value of the variable (i) will be 1; the second time round the loop its value will be 2, the third time 3, etc.... The statements within the loop, therefore, will make use of the variable to identify cells (using Cells) and put a value into them. The result of this is that starting in cell A1, the loop will fill the Range A1 to A100 with consecutive numbers starting at 1. Dim i as Byte For i = 1 To 100 Cells(i , 1).Value = i Next i The following example creates a variable named wBkCount that counts the number of open workbook. It then uses the variable (i) in a For... Next loop to save them all. Dim wBkCount as Byte Dim i as Byte wBkCount = Workbook.Count For i = 1 To wBkCount WorkBooks(i).Save Next i

Using Step
This final example uses step to create an interval of 2 in the counting. The first time round the loop, the value of the variable (i) will be 1; the second time the value of the variable will be 3 (1 + 2); the third time 5 (3 + 2), etc.... The result of this is that the column will be filled with 50 odd numbers in alternate cells.
Key Training Solutions Limited Page 97

Introduction to Excel VBA

Lesson 7 The For Loop

Dim i as Byte For i = 1 To 100 Cells(i , 1).Value = i Next i

Procedures
1. Position the cursor in the sub procedure code where you want to place the statement. 2. Type For. 3. Type a space. 4. Create a variable by entering a name for it, eg. counter 5. Type =. 6. Type a number from where you want the loop to start. 7. Type To. 8. Type a number from where you want the loop to end. 9. If the loop must count between start and end with an interval that is not equal to 1 (the default), type a space. 10. Type Step. 11. Type a space. 12. Type a number for the interval that you want the loop to count. 13. Press Enter. 14. Type the statements that you want the sub procedure to repeat as defined by the For ... To statement. 15. Press Enter. 16. Type Next. 17. Type a space. 18. Type the variable name used in the For... To statement at the beginning of the loop 19. Press Enter. 20. Add additional code as necessary.

Key Training Solutions Limited

Page 98

Introduction to Excel VBA

Lesson 7 The For Loop

Nested For... Next Loops


Nesting loops means placing one inside another so that the values of two separate looping variables can be used in the statements. The example below fills each cell in rows 1 and 2 with a random value between 1 and 100. Dim firstLoopingVar as Byte Dim secLoopingVar as Integer For firstLoopingVar = 1 To 2 For secLoopingVar = 1 To 256 Cells(firstLoopingVar,secLoopingVar).Value = Rnd * 100 Next secLoopingVar Next firstLoopingVar The For... Next loop does not necessarily have to start counting from 1, it can start at any value including negatives. Eg. For counter = 10 to 1000 For counter = -15 To 50 For counter = - 100 To -10 The For... Next loop, however, will fail if the start number is higher than the end number, eg. For counter = 100 To 1.

USING A FOR EACH... NEXT LOOP


Discussion
The For Each Next loop allows a series of statements to be repeated for each item in a group.The syntax is as follows: For Each element In collection (or array) statements Next element This begs the question: What is a collection (or array) and how do we define an element in it?

Key Training Solutions Limited

Page 99

Introduction to Excel VBA

Lesson 7 The For Loop

Well, think of collection (or array) as a container with lots of sections in it, rather like a pigeon hole unit in a post room. Each element is one of the holes in the unit. The For Each ... Next loop repeats the statements for as many pigeon holes as there are in the unit! So, how do we define the pigeon hole unit in Excel? In many cases it will be a range of cells or another collection of objects. The analogy, therefore, works well because if we take a range of cells, they do, indeed, resemble a pigeon hole unit with each cell representing one of the holes.

Collection, therefore, might be expressed as Range(A1:A10). Each element in the collection (each cell) is expressed as a variable using the variable naming rules described on page 87. The variable would be declared as Object. Hence, a For Each... Next loop that uses a range as the collection will adopt the following form: . Dim specificCel as Object For Each specificCel in Range(A1:C4) The loop works rather like a check sheet, where each cell gets ticked as done once the statement(s) have been executed on it. The order in which the elements are ticked starts with the cell in the top left corner and continues from left-to-right along the top row. It then repeats from left-to-right going down the columns.

The following example uses a For Next...Each loop to enter a zero into any blank cells in the range B2 to D200.

Key Training Solutions Limited

Page 100

Introduction to Excel VBA

Lesson 7 The For Loop

Dim specificCel as Object For Each specificCel in Range(B2:D200) (For each element in the collection, ie. for every cell in the range B2 to D200) If specificCel.Value = then (If the cell is empty then...) specificCel.Value = 0 (Enter a value of zero in it) End if Next specificCel (Return to For Each and check if all the cells (elements) in the range (collection) have been tested. If TRUE, continue below Next. If FALSE, repeat the statements.) Note how the variable defined in the first line MUST be used as the object in the repeating statements. If ActiveCell had been used, the statements inside the loop would have been ignored and the If block executed on whichever cell was active when the macro was run. The For Each ... Loop is more powerful that the Do loops and even (to an extent) the For Next loop. It is faster because there is no physical selecting of objects, it is all done in the computers memory. It is much easier and more convenient to use to carry out looping actions when there is a mixture of columns and rows. Try using a Do loop or a For Next loop in the above example! It can be used to loop through other types of object collections in a way that other loops can not.

Other Collections
We have examined above the use of a range as the collection (or array). Examples of some other collections that can be used is given below. Object Workbooks (Excel files) Collection WorkBooks Syntax example Dim wBk as Object For Each wBk in WorkBooks wBk Save Next wBk (Saves every open workbook)

Key Training Solutions Limited

Page 101

Introduction to Excel VBA

Lesson 7 The For Loop

WorkSheets

Sheets

Dim sht As Object For each sht in Sheets sht.Tab.Color = vbBlue Next sht (Colours each sheet tab of the active workbook blue)

Charts (Graphs)

ChartObjects

Dim chrt As Object For Each chrt in ActiveSheet.ChartObjects chrt.Height = 100 chrt.Width = 200 Next chrt (Makes all charts on the active sheet the same height and width. The unit is measured in pixels and the actual size on screen will depend on the video resolution being used)

Add Ins

AddIns

Dim aIn as Object For Each aIn in AddIns aIn.Installed = False Next aIn (Turns off all currently loaded add-ins)

Toolbars (Excel 2000 2003 only)

CommandBars

Dim tBar as Object For Each tBar in CommandBars tBar.Reset Next tBar (Resets each Excel toolbar to its default)

Using Selection in a For Each... Next loop


The collection in a For Each... Next loop does not need to be specifically given. You can use a Selection of valid objects either that has been selected by the sub procedure or that was selected by the user before the macro was run. In the following example, a range of cells is first selected. The loop then acts on the selection. Dim specificCel As Object Range(B2:C15).Select For Each specificCel in Selection specificCel.Font.Size = 20 Next specificCel
Key Training Solutions Limited Page 102

Introduction to Excel VBA

Lesson 7 The For Loop

In the following example, the user has already selected several charts on a worksheet (by clicking the first one and then holding down the SHIFT key and clicking all the others). The loop then changes their background colour to cyan and prints them all. Dim chrt As Object For Each chrt in Selection Chrt.Chart.ChartArea.Interior.Color = vbCyan Chrt.Chart.PrintOut Next chrt

Procedures
1. Position the cursor in the sub procedure code where you want to place the statement. 2. Type For Each. 3. Type a space. 4. Type a variable name to represent each of the elements that you want the loop to act on. 5. Type a space. 6. Type In. 7. Type the name of a valid object or reference to an object, 8. eg. Range(A1:C10) or Selection or Sheets 9. Press Enter. 10. Type the statements that you want the sub procedure to repeat as defined by the For ... Each statement. 11. Press Enter. 12. Type Next. 13. Type a space. 14. Type the variable name used in the For... Each statement at the beginning of the loop 15. Press Enter. 16. Add additional code as necessary.

Nested For Each... Next Loops


By nesting For Each... Next loops, actions can be performed on two collections simultaneously.The following example loops through every cell value in the range A1 to A6 and compares it to every cell value in range C1 to C20. If the cell values match, the matching cells in range C1 to C20 are formatted with a magenta fill colour.
Key Training Solutions Limited Page 103

Introduction to Excel VBA

Lesson 7 The For Loop

Dim firstCel As Object Dim secCel As Object For Each firstCel in Range(A1:A6) For Each secCel in Range(C1:C20) If firstCel.Value = secCel.Value Then secCel.Interior.Color = vbMagenta End If Next secCel Next firstCel

Key Training Solutions Limited

Page 104

Introduction to Excel VBA

Lesson 7 The For Loop

EXERCISE
CREATE A FOR LOOP STRUCTURE.
1. Open the file Practice Loops. Enable the macros, if prompted. 2. Test the CheckDept procedure. The macro runs just once, identifies that Davis works in the Sales department and emboldens the font in cell B5. 3. Edit the procedure as necessary so that it runs 12 times in order to check all the departments in column C. 4. Test the macro and correct any errors. 5. Save and close the file. 6. Open the file Student Grades. 7. Edit the CollegeIdentify procedure with a FOR EACH NEXT loop so that the macro runs on all the cells in range C2:C18. 8. Test the macro and correct any errors. 9. Save and close the file.

Key Training Solutions Limited

Page 105

LESSON 8 ADDING INTERACTIVITY TO MACROS


In this lesson, you will learn how to:
Create a Sub procedure that displays information on a worksheet by using the MsgBox function. Create a Sub procedure that displays a dialog box by using an InputBox function

Key Training Solutions Limited

Page 106

Introduction to Excel VBA

Lesson 8 Adding Interactivity

THE MSGBOX FUNCTION


Discussion
To display brief messages such as errors, warnings, or directions for accomplishing a task, you can use the MsgBox statement. This function displays a message in a dialog box, along with an OK button. The syntax is as follows: MsgBox prompt, buttons, title, helpfile, context Prompt, the only required argument. A string of text, surrounded by quotes, that you would like to display in the message box. Buttons, (optional), describes the number and type of buttons displayed in the dialog box; determines the icon style; determines which button is the default; and determines the modality (on/off position) of the message box. Title, (optional), displayed on the title bar of the message box. Helpfile and Context, (optional), identify which Help file to use to provide context-sensitive Help for the message box. (It is very unusual to use this because the helpfile needs to be constructed and compiled using Microsoft tools not provided with Office.

To use the message box function purely to display a message, it is only necessary to use the prompt argument, eg. : MsgBox The procedure has successfully completed

Embellishments can be added to the message box by adding an icon and a window title, eg.
MsgBox The procedure has successfully completed, vbInformation, Duplicate Checker

Key Training Solutions Limited

Page 107

Introduction to Excel VBA

Lesson 8 Adding Interactivity

Procedures
1. Position the cursor in the sub procedure code where you want to place the statement. 2. Type MsgBox. 3. Type a space. 4. Type the text string, variable name or combination of both (separated by - space ampersand space ( & )) that you wish the message box to display. 5. Press Enter. 6. Add additional code as necessary.

CREATING AN INTERACTIVE MESSAGE BOX


Discussion
The previous topic describes using a message box purely to display a message and provide an OK button to close the window. It can, however, also be used interactively in cases where a response is required from the user. : Examples might be where confirmation is required to proceed with the next part of the procedure, or in error handling (not covered on this course), eg.

Example A

Example B

To make the message box interactive, the arguments must be put inside brackets. The following code will display Example A above. MsgBox ("Do you want to continue deleting the data", vbYesNo, "Delete Confirm")
Prompt Buttons Title

Key Training Solutions Limited

Page 108

Introduction to Excel VBA

Lesson 8 Adding Interactivity

The buttons argument consists of constants or values from each of the following three groups:

Number and type of button:


Constant vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel Value 0 1 2 3 4 5 Display OK button only OK and Cancel buttons Abort, Retry and Ignore buttons Yes, No and Cancel buttons Yes and No buttons Retry and Cancel buttons

Icon style:
Constant vbCritical vbQuestion vbExclamation vbInformation Value 16 32 48 64 Display Critical Message icon. Warning Query icon. Warning Message icon. Information Message icon. Icon

Default Button:
Constant vbDefaultButton1 vbDefaultButton2 vbDefaultButton3 Value 0 256 512 Default First button is default Second button is default third button is default

The buttons argument of the message box function can hold three pieces of information separated by a plus (+) symbol. Using the following code as the buttons argument will produce Example C below. vbYesNo + vbQuestion + vbDefaultButton2

Key Training Solutions Limited

Page 109

Introduction to Excel VBA

Lesson 8 Adding Interactivity

vbQuestion vbYesNo vbDefaultButton2 (second from left)

A more concise method of writing the above sample of code would be to use the numeric values for the arguments, eg. 4 + 32 + 256 Im sure that the average user will, however, find it easier to remember the vb constants, viz. vbYesNo + vbQuestion + DefaultButton2.

Procedures
1. Position the cursor in the sub procedure code where you want to place the statement. 2. Type a variable name to store the value of whichever button is clicked in the message box, eg. response. 3. Type =. 4. Type MsgBox. 5. Type an opening bracket ( . 6. Type a speech mark (Shift 2). 7. Type a prompt for the message box, ie. the message that you want it to display, eg. Do you want to continue? 8. Type a speech mark (Shift 2). 9. Type a comma. 10. Type the necessary value to indicate which buttons you want the message box to display, eg. vbYesNo. 11. If you wish to add an icon and/or default button to the message box, type a plus symbol (+). 12. Type the necessary value to indicate which icon to display, eg. vbQuestion 13. Type a plus symbol (+). If you dont wish to add an icon and/or a default button to the message box, go to 15 below.

Key Training Solutions Limited

Page 110

Introduction to Excel VBA

Lesson 8 Adding Interactivity

14. Type the necessary value to indicate which default button you wish to set, eg.vbDefaultButton2 15. Type a comma. 16. If you wish to add a title to the message box, type a comma 17. Type a speech mark (Shift 2). 18. Type the title text. 19. Type a speech mark (Shift 2). 20. Type a closing bracket ) . 21. Press Enter. 22. Add additional code as necessary. If you do not wish to add a title to the message box, go to 20 below.

Responding to an Interactive Message Box


The value returned by the function depends upon which button is pressed. The value is returned as a constant, which is equal in value to a number. The constant or the value can be tested by the procedure, usually by means of an IF statement. : Constant vbOK vbCancel vbAbort vbRetry vbIgnore vbYes vbNo Value 1 2 3 4 5 6 7 Button Selected OK Cancel Abort Retry Ignore Yes No

In the following example, the message box offers a yes/no response. If the user clicks yes, then the procedure will delete all the data from the sheet. If the user clicks no, the procedure will terminate. If MsgBox (Do you want to delete all data, vbYesNo + vbCritical) = vbYes Then ActiveSheet.Cells.Clear End If The result of the message box (ie. whether the yes or no button is clicked) can be stored in a variable and the code could also be written:
Key Training Solutions Limited Page 111

Introduction to Excel VBA

Lesson 8 Adding Interactivity

Dim response as Byte response = MsgBox (Do you want to delete all data, vbYesNo + vbCritical) If response = vbYes Then End If or If response = 6 Then ActiveSheet.Cells.Clear

Procedures
1. (The procedure below assumes a message box containing Yes and No buttons. It can be adapted, however, to respond to any set of buttons (eg. vbOKCancel, vbRetryCancel etc.)) 2. Position the cursor in the sub procedure code where you want to place the statement. 3. Create an interactive message box as described in the previous topic of this lesson. 4. Press Enter. 5. Type If. 6. Type a space. 7. Type the variable name that you have used to store the response from the message box. 8. Type a space. 9. Type = vbYes. 10. Type a space. 11. Type Then. 12. Type the statements that you want the sub procedure to perform if the user has clicked the Yes button. 13. Press Enter. 14. Type Else. 15. Press Enter. 16. Type the statements that you want the sub procedure to perform if the user has clicked the No button. 17. Press Enter. 18. Type End If. 19. Press Enter. 20. Add additional code as necessary.

Key Training Solutions Limited

Page 112

Introduction to Excel VBA

Lesson 8 Adding Interactivity

CREATING A CUSTOM INPUT BOX


Discussion
The InputBox function displays a prompt in a dialog box prompting the user for data. This data can then be stored in a variable. The dialog box has an OK button, a Cancel button and an optional Help button. The syntax for the InputBox statement is: InputBox (prompt, title, default, xpos, ypos, helpfile, context). Prompt, the only required argument. A text string, surrounded by quotes, that you would like to display in the dialog box. The maximum length is 1024 characters. Title, (optional), represents what is displayed on the title bar of the dialog box. The default title will be Microsoft Excel. Default, (optional), represents a string expression that is displayed in the text box as the default response, if no other input is provided. If you omit the default, the text box is displayed as empty. xpos, and ypos, (optional), are numeric expressions that specify the horizontal and vertical distances from the top left corner of the screen where the top left corner of the input box will be located. If xpos and ypos are omitted, the dialog box is centred horizontally on the screen, about one-third of the way down from the top. (It is very unusual to use this argument, because the exact position varies between types of monitor, even though Excel tries to compensate for this). The measurement unit used is twips, and there are approximately 10 twips to a pixel! Helpfile, and context, (optional), identify which Help file to use to provide context-sensitive Help for the dialog box. (It is very unusual to use this, because the helpfile needs to be constructed and compiled using Microsoft tools not provided with Office).

The following example displays the following dialog box. The users response is stored in a variable called yName. Dim yName as String yName = InputBox("Please Enter Your Name")

Key Training Solutions Limited

Page 113

Introduction to Excel VBA

Lesson 8 Adding Interactivity

If the user clicks OK or presses Enter, the InputBox function returns to the variable yName whatever was typed in the text box. If the user clicks Cancel or presses Esc, the InputBox function returns a zero length (empty) string. The following example adds a title at the top of the input box window and adds a default text string in the text box. Dim yName as String
yName = InputBox("Type your company name", "Company Name Input", "Key Training")

The input box may be invoked wherever there is a need to prompt the user for information to use in a sub procedure. The sample code below gives two examples of how it might be used. Sample A Prompt the user for a name to give the current sheet Dim shtName as String shtName = InputBox(What name do you wish to give the current worksheet?) ActiveSheet.Name = shtName Or... Dim shtName as String
ActiveSheet.Name = InputBox(What name do you wish to give the current worksheet?)

Key Training Solutions Limited

Page 114

Introduction to Excel VBA

Lesson 8 Adding Interactivity

Sample B Prompts user for two inputs, carries out a calculation and returns the result in a message box and in cell A1. Dim amount as Single Dim rate as Single amount = InputBox (Enter your sales figure) rate = InputBox(Enter your commission rate as a decimal percentage, eg. 0.15) commission = amount * rate MsgBox Your commission for this sale is & commission Range(A1).Value = commission Or... MsgBox Your commission for this sale is & Format(commission,#,##0.00) Range(A1).Value = Format(commission,#,##0.00)

Procedures
1. Position the cursor in the sub procedure code where you want to place the statement. 2. Type a variable name in which the data entered in the input box will be stored. 3. Type =. 4. Type InputBox. 5. Type an opening bracket ( . 6. Type a speech mark (Shift 2). 7. Type the text that you want the input box to display. 8. Type a speech mark (Shift 2). 9. Type a comma. 10. If you wish to add a title to the input box, type a comma 11. Type a speech mark (Shift 2). 12. Type the title text. 13. Type a speech mark (Shift 2). 14. Type a comma. If you dont wish to add a title to the input box, go to 14 below.

Key Training Solutions Limited

Page 115

Introduction to Excel VBA

Lesson 8 Adding Interactivity

15. If you wish to add default text to the input box, type a comma 16. Type a speech mark (Shift 2). 17. Type the default text. 18. Type a speech mark (Shift 2). 19. Type a comma . 20. If you wish to specify an x and y position for the message box, type a comma. 21. Type a value for the x position. This is measured in Twips and there approx. 10 Twips to a pixel. The x position is measured down from the top left-hand corner of the Excel window. 22. Type a comma. 23. Type a value for the y position. This is measured in Twips and there approx. 10 Twips to a pixel. The y position is measured to the right from the top left-hand corner of the Excel window. 24. Type a closing bracket ) . 25. Press Enter.

If you do not wish to add default text to the message box, go to 19 below.

If you do not wish to specify an x and y position for the message box, go to 24 below.

26. Add additional code as necessary.

Key Training Solutions Limited

Page 116

Introduction to Excel VBA

Lesson 8 Adding Interactivity

EXERCISE
USING INTERACTIVITY
1. Open the file MsgBoxButtons. Enable the macros, if prompted. 2. Click the Add Forecast macro button on the Buttons sheet. This copies and pastes data from the Forecasts sheet. 3. Click the Clear Sheet macro button. This deletes out all data from the Buttons sheet. 4. Edit the Add_Forecast and Clear_Forecast procedures so that a message box appears, asking the user if: a) they are sure they want to continue; b) giving them Yes and No buttons to choose from; c) giving a message box title of "Confirm." 5. Run both macros to check that they work. 6. Run the Add_Forecast procedure. 7. Create a new procedure called InputData that: prompts the user with two Input Boxes for values to enter for the projected incomes of the two countries (Great Britain and United States). have as its title, the name of the country to which it applies. enters the values in the appropriate cells (E7 and E8). 8. Assign the procedure to a worksheet button. 9. Run the macro to check that the procedure works, entering some made up information of your own into each input box. 10. Save and close the file.

Key Training Solutions Limited

Page 117

APPENDIX I - MACRO SECURITY


In this lesson you will learn:
To understand Excels macro protection settings To adjust macro protection setting to a suitable level To understand, use and create trusted locations

Key Training Solutions Limited

Page 118

Introduction to Excel VBA

Appendix I - Security

SECURITY LEVELS
Discussion
While many macros are simply recordings of your keystrokes and mouse actions, VBA developers can write macros that carry out many commands on your computer. As a result, hackers can introduce harmful code onto your computer by writing macros that release a virus when run. When opening an Excel file containing macros, therefore, Excel uses various criteria to ensure any macros contained therein are safe. The level and thoroughness at which Excel does this is determined by the security settings in force on your computer. The criteria for this varies depending on whether the workbook is being opened from a trusted location and/or if it is digitally signed. 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.

Security Levels - Excel 2003, 2002(XP) & 2000. Very High (Excel 2003 only) Only macros installed in trusted locations will be allowed to run. All other signed and unsigned macros are disabled. When attempting to open a workbook containing macros, the following message will appear:

High

Unsigned macros are automatically disabled and the file is opened.


With signed macros, the source of the macro and the status of the signature determine how signed macros are handled. When attempting to open a workbook containing macros, no message will appear.

Medium

With unsigned macros, the user is prompted to enable or disable the macros. When attempting to open a workbook containing unsigned macros, the following message will appear.

Key Training Solutions Limited

Page 119

Introduction to Excel VBA

Appendix I - Security

With signed macros, the source of the macro and the status of the signature determine how signed macros are handled. Low When security it set to low, all macros are treated equally regardless of origin or certificate status. With low security, you receive no prompt or signature validation and macros are automatically enabled. Use this setting only if you are certain that all macros in your files are from trusted sources. In Excel 2007, macro security has changed significantly. Although the security levels are comparable with earlier versions of Excel, the way in which Excel 2007 warns you about potential risks has changed. Instead of a message box appearing on the screen, a Message Bar appears above the work area at the left and below the Ribbon. These are referred to as notifications.

Excel 2007 macro security notification Security Levels (Excel 2007) . Disable all macros without notification Click this option if you don't trust the macros. All macros and security alerts about macros are disabled. If there are documents that contain unsigned macros that you do trust, you can put those documents into a trusted location (see page 122). Documents in trusted locations are allowed to run without being checked by the Trust Center security system. Disable all macros with notification (default) With unsigned macros, the user is prompted to enable or disable the macros.

On clicking the Options... button, the following dialog box appears:

Key Training Solutions Limited

Page 120

Introduction to Excel VBA

Appendix I - Security

Disable all macros except digitally signed macros

With signed macros, the source of the macro and the status of the signature determine how signed macros are handled. When security it set to low, all macros are treated equally regardless of origin or certificate status. With low security, you receive no prompt or signature validation and macros are automatically enabled. Use this setting only if you are certain that all macros in your files are from trusted sources.

Enable all macros

In Microsoft Office 2003 or later, a component checks all XML files that have references to XSL files for script that could be unsafe. If macro security is set to High, running this script is disabled. If macro security is set to Medium, the user is asked whether or not to run script in XSL files. If macro security is set to Low, the script is run.

CHANGING MACRO SECURITY SETTINGS


Discussion
If youre creating your own macros, or the macros that you run are from a reliable source within your own workplace, youll probably want to lower the protective security settings. If, however, the macros you use are often received from unknown sources, you may wish to increase it.

Procedures (Excel Versions 2000 - 03)


1. Click the Tools menu. 2. Point at Macro. 3. Select Security....

Key Training Solutions Limited

Page 121

Introduction to Excel VBA

Appendix I - Security

4. Select the required security level option. 5. Click OK.

Procedures (Excel 2007)


1. Click the Microsoft Office button. 2. Click Excel Options. 3. Select Trust Center in the pane at the left. 4. Click the Trust Center Settings... button. 5. Select Macro Settings in the pane at the left. 6. Select the desired option in the Macro Settings section. 7. Click OK. 8. Click OK again.

TRUSTED LOCATIONS (EXCEL 2007)


Discussion
The trusted locations feature in Office 2007 enables you to designate folders on your hard disk or on a network share as trusted file sources. When a folder is designated as a trusted file source, any file that is saved in the folder is assumed to be a trusted file. When a trusted file is opened, all content in the file is enabled and active, and users are not notified about any potential risks that might be contained in the file, such as unsigned macros, ActiveX controls, or links to content on the Internet. Storing Excel workbooks in a trusted location facilitates opening them and enabling any macros they contain.

Procedures
1. Click the Microsoft Office button. 2. Click Excel Options. 3. Select Trust Center in the pane at the left. 4. Click the Trust Center Settings... button. 5. Select Trusted Locations in the pane at the left, if necessary. 6. Note the existing default trusted locations and assess whether it is practical to use them. 7. If the answer to 6 above is yes, then click Cancel and leave the settings unchanged. 8. If the answer to 6 above is no, then
Key Training Solutions Limited Page 122

Introduction to Excel VBA

Appendix I - Security

9. Click the Browse... button. 10. Navigate to the folder that you want to make a trusted location. 11. Click OK. 12. Click the Subfolders of this location are also trusted check box, if desired. 13. Enter a description for the location, if desired. 14. Click OK. 15. Click OK. 16. Click OK. In Excel 2003 the only trusted location is the XLSTART folder.
Documents and Settings\<user name>\Application Data\Microsoft\Excel\XLSTART

This is normally a hidden folder and in order to see it, is has to be unhidden as follows: Open an Explorer window Click Tools Select Folder Options Open the View tab Enable the Show hidden files and folders option

Click OK

Key Training Solutions Limited

Page 123

Introduction to Excel VBA

Index

INDEX
Coding ActiveCell ................................................. 57 capitalisation ............................................. 60 comments .................................................. 60 concatenation character ............................ 62 indentations............................................... 60 line breaks ................................................. 61 Run-time error .................................... 65, 66 Selection ................................................... 56 statements, definition ................................ 59 sub procedures, definition......................... 58 the OFFSET function................................ 64 white space ............................................... 60 With... End With block ....................... 62, 63 Control Structures Do Loop .............................................. 81, 82 ElseIf................................................... 77, 78 For Each examples.......................... 101, 102 For Each loop ........................... 99, 100, 103 For Next examples .............................. 96, 97 For Next loop ...................................... 96, 98 If...Then .................................. 73, 76, 78, 80 If...Then...Else .......................................... 76 nested For Each examples ...................... 103 nested For Each loops ............................. 103 nested For Next examples......................... 99 nested For Next loops ............................... 99 Select Case.......................................... 79, 80 using Step with For Next .......................... 97 Input Box definition................................................. 113 examples ................................................. 113 Keywords End Sub .................................................... 58 Sub ............................................................ 58 Macro buttons copying ..................................................... 39 creating ..................................................... 37 creating in Excel 2000 - 03 ....................... 37 creating in Excel 2007 .............................. 38 deleting ..................................................... 42 moving ................................................ 40, 41 sizing................................................... 40, 41 using ......................................................... 37 Macros assigning a shortcut key ............................ 30 assigning to a menu .................................. 34 assigning to a toolbar button ..................... 31 defining ....................................................... 6 deleting custom button.............................. 36 deleting from a menu ................................ 36
Key Training Solutions Limited

description .................................................. 8 naming ........................................................ 7 opening ............................................... 13, 16 personal macro workbook .......................... 7 recording .................................................... 6 running ..................................................... 10 saving ................................................. 12, 13 security warnings Excel 2000 - 03 ........... 14 security warnings Excel 2007 .................. 14 shortcut key ................................................ 7 storing......................................................... 7 using relative references ..................... 11, 12 visual basic toolbar..................................... 9 Menus adding a macro command ........................ 34 creating from new .................................... 35 deleting macro commands........................ 36 Message Box adding interactivity................................. 108 buttons .................................................... 109 default button ......................................... 109 definition ................................................ 107 examples................................................. 107 icons ....................................................... 109 interactive use examples ........................ 111 Methods Activate .................................................... 54 Add ........................................................... 53 arguments ........................................... 53, 54 arguments, examples ................................ 53 Copy ......................................................... 54 definition ............................................ 46, 49 frequently used ......................................... 50 Object Browser ........................................ 68 Open ......................................................... 55 Paste ......................................................... 54 returning ................................................... 52 Select ........................................................ 54 Modules copying ..................................................... 25 deleting ..................................................... 27 inserting .................................................... 24 renaming................................................... 26 Objects ActiveCell .......................................... 56, 57 ActiveSheet ........................................ 56, 57 ActiveWorkBook ..................................... 56 Application ......................................... 46, 50 Cells ................................................... 49, 57 collections ................................................ 47 definition .................................................. 46
Page 124

Introduction to Excel VBA

Index

examples ............................................. 55, 56 frequently used ......................................... 46 Object Browser ......................................... 68 Range .................................................. 47, 51 referring by index number ........................ 48 the object model........................................ 46 WorkBooks ............................. 46, 48, 49, 50 WorkSheets............................. 47, 48, 49, 50 Personal Macro Workbook definition................................................... 17 saving ........................................................ 17 storing macros in ........................................ 7 Properties definition............................................. 46, 49 frequently used ......................................... 50 Object Browser ......................................... 68 returning ................................................... 52 Quick Access Toolbar adding a custom button ............................. 32 Ribbon (Excel 2007) adding developer tab ................................. 38 Security change settings........................................ 121 definition................................................. 119 digital signature ...................................... 119 levels Excel 2000 - 03 ............................ 119 levels Excel 2007 .................................... 120 notifications Excel 2007 ......................... 120 trusted locations Excel 2003 ................... 123

trusted locations Excel 2007 .................. 122 Toolbars adding a custom button ............................ 31 creating from new .................................... 33 deleting custom buttons............................ 36 Variables assigning values ....................................... 88 creating ..................................................... 87 data types table ......................................... 92 declaring ................................................... 91 definition .................................................. 87 error messages .......................................... 93 examples....................................... 88, 89, 90 naming ...................................................... 88 the DIM statement .................................... 91 types ......................................................... 91 Visual Basic Editor Add-ins ..................................................... 23 code pane.................................................. 22 launching .................................................. 21 modules .............................................. 23, 24 navigating ................................................. 22 Object Browser ........................................ 67 Project Explorer ....................................... 22 properties .................................................. 22 Visual Basic for Applications definition .................................................... 6 Visual Basic ............................................... 6

Key Training Solutions Limited

Page 125

Introduction to Excel VBA

Index

HELP SERVICE
Key Training Solutions Limited offers a post-training email Help Service, providing support for anyone who has a query regarding the content of a desktop training course they have attended at Key Training.

When is it available?
The Help Service Operates during normal business hours: Monday to Friday 09:00 - 17:00 To access the help service, send an e-mail to helpservice@keytraining.co.uk

Course Query
It is essential to include the following information in your e-mail so that your query can be dealt with promptly: Full title of the course you attended (e.g. Word 2003 Level 1 or Excel 2007 Level 3, etc). As much information as possible regarding the problem or query to be solved. Your contact details (including best time for us to contact you).

Please do not send any attachments with your e-mail, (we will request a copy of the file if required at a later stage)

Course Data Files


If your request is for a copy of the exercise files used during a course you have recently attended through Key Training, then can you please ensure that you provide in your e-mail to the above address: Full title of the course you attended (e.g. Word 97 Level 1 or Excel 2000 Level 3 etc). The date you attended the course. The name of your trainer.

Course Enquiry
The Help Service is also available if you would like advice on which level of course yourself or a colleague would be best suited to attend. You will need to include in an e-mail to the above address: The application and version you are using or looking to use (e.g. Word 2007). Your telephone number. Your company name. The best time for us to contact you.

Please note: We will endeavour to respond to all Help Service requests within 24 hours of receipt (all requests received on a Friday will be dealt with on the following Monday).
Key Training Solutions Limited Page 126

Вам также может понравиться