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