Microsoft Excel VBA Free Training Manual - Solutions

113 downloads 1036 Views 670KB Size Report
guide to the course and does not replace the documentation provided with the ... Excel's object model, exposes very powerful data analysis objects, such as ...
PREMIER

Microsoft Excel 2007 VBA (Macros) Premier Training Limited 4 Ravey Street London EC2A 4QP Telephone +44 (0)20 7729 1811 www.premcs.com

Excel 2007 VBA

TABLE OF CONTENTS INTRODUCTION ........................................................................................ 1  MODULE 1 - OVERVIEW OF VISUAL BASIC.......................................... 2  MODULE 2 - INTRODUCTION TO VBA ................................................. 12  MODULE 3 - OVERVIEW OF VISUAL BASIC EDITOR ......................... 24  MODULE 4 - INPUTS AND OUTPUTS ................................................... 34  MODULE 5 - VARIABLES ....................................................................... 50  MODULE 6 - CONTROL STRUCTURES AND LOOPS ......................... 61  MODULE 7 - OBJECTS, PROPERTIES, METHODS, EVENTS AND ERROR HANDLING ................................................................................ 75  MODULE 8 - DEBUGGING ........... ERROR! BOOKMARK NOT DEFINED.  MODULE 9 - FORMS (DIALOG BOXES) ............................................... 81  INDEX..................................................................................................... 100 

Excel 2007 VBA

INTRODUCTION This manual is designed to provide information required when using Excel 2007. This documentation acts as a reference guide to the course and does not replace the documentation provided with the software. The documentation is split up into modules. Within each module is an exercise and pages for notes. There is a reference index at the back to help you to refer to subjects as required. These notes are to be used during the training course and in conjunction with the Excel 2007 reference manual. Premier Computer Solutions holds the copyright to this documentation. Under the copyright laws, the documentation may not be copied, photocopied, reproduced or translated, or reduced to any electronic medium or machine readable form, in whole or in part, unless the prior consent of Premier Computer Solutions is obtained.

© Premier Training Limited

Page 1

Excel 2007 VBA

Module 1 - Overview of Visual Basic A macro is a sequence of instructions that can be automatically executed in order to automate frequent or complicated tasks. Macros are written in a programming language called Visual Basic and can be created by recording a task or by writing the Visual Basic program or by a combination of the two. Macros can be added to menus, assigned to keys or buttons or made to run automatically.

Objects and Hierarchies When developing applications in Excel, it’s helpful to think in terms of objects, excel elements that you can manipulate through a macro. On the corresponding pages you will see a collection of objects available in Excel. The hierarchy comprises Excel’s object model. Excel’s object model, exposes very powerful data analysis objects, such as worksheets, charts, pivot tables, scenarios, and financial functions amongst others. Objects act as containers for other objects such as Workbook and Command Bar objects. A worksheet object can contain objects such as Range objects and so on.

Methods Objects have Methods, and a method is an action that is performed with the object. To clear the contents of a cell, we can use the method ClearContents, which is a method for a range object. Another key concept of Excel VBA is collections. A collection is a group of objects of the same class. For example Worksheets is a collection of all Worksheet objects in a Workbook object.

© Premier Training Limited

Page 2

Excel 2007 VBA

Properties Every object has properties. An example would be that a range object has a property called Value. You can display the value or set the property value to a specific value. The following code uses the Msgbox function to display a value; Sub ShowValue() Msgbox Worksheets(“Sheet1”).Range(“A1”).Value End Sub

Microsoft Excel Objects

:

See Table1

:

See Table2

Object and collection Object only

© Premier Training Limited

Page 3

Excel 2007 VBA

Table 1: Microsoft Excel Objects (Worksheet)

Object and collection Object only

Table 2: Microsoft Excel Objects (Charts)

© Premier Training Limited

Page 4

Excel 2007 VBA

Legend Object and collection Object only

© Premier Training Limited

Page 5

Excel 2007 VBA

Click arrow to expand chart

Objects, Properties and Methods An object is something that is controlled by Visual Basic, for example a worksheet or a range of cells. An object is controlled using properties and methods. A property is a characteristic of the object that can be set in a certain way. For example a worksheet has the visible property indicating whether or not the worksheet is visible; a range of cells has the height property indicating the height of the rows in the range. A method is an action that can be performed by the object. For example, a worksheet can recalculate formulae; a range of cells has the copy method. Properties have values that are set or returned. Methods are actions that an object can perform. Most properties have a single value, methods can take one or more arguments and may return a value. One of the following is usually performed by statements in a procedure: Set the value of one of the properties of an object. Return the value of one of the properties of an object. Perform a task on an object by using a method of the object. For example, a cell can be tested to see if it is empty by returning the value property. If it is not empty the cell can be cleared using the ClearContents method. A new formula can entered into the cell by setting the value property. © Premier Training Limited

Page 6

Excel 2007 VBA Sub TestEmpty() If IsEmpty(ActiveCell.Value) Then ActiveCell.Value = 10 Else ActiveCell.ClearContents End If End Sub

Controlling Objects with their Properties An object is changed by changing it’s property. The current property value can be tested and a new value for the property can be set. A property is usually one of the following: A numeric value A character string A True or False value A property is referred to in a statement as: Object.Property

Setting a Property Value To set a new value for the property, use the following statement: Object.Property = expression For example to set properties for the current active cell: ActiveCell.Rowheight = 14 ActiveCell.Value = "Annual Totals" ActiveCell.Locked = True

Returning a Property Value The current property of a value can be returned and is usually assigned to a variable for further testing using the following statement: variable = Object.Property For example: © Premier Training Limited

Page 7

Excel 2007 VBA row_height = ActiveCell.RowHeight A property can be set using the value of another property without assigning to a variable in between. For example, to assign the value in the current active cell into cell C1 on the current worksheet: Cells(1, 3).Value = ActiveCell.Value

Performing Actions with Methods A method performs an action on an object. For example, Clear is a method that can be applied to clear the contents of a range of cells. Certain methods can also return values, for example the CheckSpelling method which performs a spell check on a range of cells, also returns the value True or False depending on whether the text is spelt correctly.

Using Methods As well as possibly returning values a method may require certain arguments, this is referred to as the method taking arguments. The syntax of the statement depends on whether a method takes arguments: A method that doesn’t take arguments is written: Object.Method For example, to justify a range of cells called Costs: Costs.Justify A method that does take arguments is written: Object.Method argument list For example to name a selection of cells using the labels in the top cell of the selection: Selection.CreateNames True, False, False, False As the arguments are optional this could also be written as: Selection.CreateNames True If a method returns a result and the result is to be saved, then

© Premier Training Limited

Page 8

Excel 2007 VBA the arguments that the method takes must be enclosed in parenthesis. For example to save the result of the InputBox method in a variable called SalesData: SalesData =InputBox ("Enter the sales data")

Using Named arguments Some methods take several arguments some of which are optional and can be omitted. For example the CreateNames method has four arguments most of which can be omitted in normal use. The method can be written to just include the relevant arguments but this is not always very clear: Selection.CreateNames True It may be preferable to write the method statement using named arguments: Selection.CreateNames Top:=True Named arguments allow the method to be written with any of the required arguments in any order. The value is assigned to the named argument using the := operator. They make the code much easier to understand and are less prone to error than an argument list where the arguments must be in the correct order and may be accidentally omitted.

Workbooks and Sheets Activating a Workbook Activating a workbook using the Activate method puts the workbook in the active window. The following procedure activates the open workbook named “MyBook.xls”. Workbooks("MyBook.xls").Activate

Activating a Worksheet

© Premier Training Limited

Page 9

Excel 2007 VBA The following example activates Sheet1 in the workbook “MyBook.xls”: Workbooks("MyBook.xls").Worksheets("Sheet1").Activate The following example selects cells A1:C3 on Sheet1 and then makes cell B2 the active cell: Worksheets("Sheet1").Activate Range("A1:C3").Select Range("B2").Activate The following example inserts “Hello” in the cell B1 on the first sheet: Worksheets(1).Range(“B1”).Value = “Hello”

ThisWorkBook The ThisWorkBook property refers to the workbook containing the macro code. ThisWorkbook is the only way to refer to an add-in workbook from inside the add-in itself. The ActiveWorkbook property does not return the add-in workbook (it returns the workbook calling the add-in), and the Workbooks method may fail because the workbook name probably changed when the add-in was created. ThisWorkbook always returns the workbook where the code is running. For example, use the following code to activate a dialog sheet stored in the add-in workbook: ThisWorkbook.UserForm1.Show The following example closes the workbook that contains the example code:

ThisWorkbook.Close

Performing Multiple actions on an Object It may be necessary for a procedure to perform several different actions on the same object. For example, the following may need to be performed to the active cell: ActiveCell.Formula = "=NOW()" ActiveCell.NumberFormat = "dd/mm/yy"

© Premier Training Limited

Page 10

Excel 2007 VBA ActiveCell.Font.Name = "Arial" ActiveCell.Font.Bold = True ActiveCell.Font.Size = 14 Because all the statements refer to the same object, it is possible to use the With statement to indicate that a series of statements are all to be performed to one object: With ActiveCell .Formula = "=NOW()" .NumberFormat = "dd/mm/yy" .Font.Name = "Arial" .Font.Bold = True .Font.Size = 14 End With The With statement makes the code easier to write, easier to read and is more efficient when running the macro. With statements can be nested and the above example could be written as: With ActiveCell .Formula = "=NOW()" .NumberFormat = "dd/mm/yy" With .Font .Name = "Arial" .Bold = True .Size = 14 End With End With

© Premier Training Limited

Page 11

Excel 2007 VBA

Module 2 - Introduction to VBA Recording a Macro A macro can be easily created by instructing Excel to record a series of routine actions. This is very useful for repetitive tasks. •

To record a macro:

1. Choose Tools Ö Macro Ö Record Ne.w Macro.

2

In the Macro name text box, type a name for the macro. The macro name can contain letters, numbers and underscores; it must begin with a letter. The name cannot contain spaces or punctuation marks. Type a brief description of the macro in the Description box, Excel creates it’s own default description.

3.

To run the macro with a shortcut key type a letter in the Shortcut key box. The shortcut will be assigned to [CTRL]+[letter]. Hold [SHIFT] while typing the letter in the Shortcut key box to assign the shortcut to [CTRL]+[SHIFT]+[letter].

4. Choose the OK button to start recording the macro.The Stop Recording toolbar appears on the screen, and the word Recording appears in the status bar. 5. Perform the actions that are to be recorded. 6. Click the Stop Recording button from the Stop

© Premier Training Limited

Page 12

Excel 2007 VBA Recording toolbar or choose Tools Ö Macro Ö Stop Recording, when the macro is finished.

Running a Macro To run a macro: If a shortcut key was assigned to the macro, then press the shortcut key. Otherwise: 1. Choose Tools Ö Macros or press [ALT]+[F8]. 2. Type the macro name or select it from the list. 3. Choose the Run button. A macro can be assigned to a menu item, a button or another graphic object providing a simple and convenient way of running the macro.

ASSIGNING MACROS TO BUTTONS AND OBJECTS Assigning a Macro to a Button on a Sheet A button can be created on a worksheet and a macro assigned to it. The macro will be available whenever the workbook is open. To create a button on a sheet: 1. Choose the Button tool on the Forms toolbar. The mouse pointer is replaced by a cross-hair. 2. Move the cross-hair to where the corner of the button should be. 3. Drag until the button is the correct size and shape and release the mouse button. The Assign Macro dialog box appears:

© Premier Training Limited

Page 13

Excel 2007 VBA

To assign an existing macro to the button: 1. Type the macro name or select it from the Macro Name list. 2. Choose the OK button. 3. To assign a new macro to the button: 4. Choose the Record button and follow the steps for recording a new macro. 5. To run the macro: 6. Click the button to which the macro is assigned. 7. To alter the text or appearance of a button: 8. Select the button by holding down [CTRL] and clicking the left mouse button. 9. Alter the button text by typing new text. 10. Change the font or alignment of the button text by choosing Format Ö Control from the shortcut menu.

Assigning a Macro to a Drawn Object on a Sheet Macros can be assigned to any worksheet object by choosing Assign Macro from the object’s shortcut menu.

Assigning a Macro to a Button on a Toolbar If a macro is assigned to a button on a toolbar, the macro is

© Premier Training Limited

Page 14

Excel 2007 VBA available at any time and for every sheet in the workbook, provided the toolbar is displayed. The workbook containing the macro is automatically opened, if it is not already open, when the button is clicked from another workbook. A macro is usually assigned to an unused custom button, but can be assigned to a built in button overriding the button’s normal function.

Customising a Toolbar Change, or customise, a toolbar so it contains buttons for most often used commands or macros. To add a button to the toolbar: 1. Choose the Commands tab of Tools Ö Customize.

2. From the Categories list box, select Macros. 3. Drag the Custom Button from the Commands list box over the toolbar and then release the mouse. 4. To select a different button image for the new button, right-click the new button and choose Change Button Image. Select a button image. 5. Choose the Close button.

Creating a Toolbar © Premier Training Limited

Page 15

Excel 2007 VBA Buttons can only be added to existing toolbars. It may be necessary to create a new toolbar before adding a button to it. To create a new toolbar: 1. Choose the Toolbars tab of Tools Ö Customize. 2. Click the New button and enter a name for the new toolbar.

3. Choose the OK button.

Button Image Editor Excel is supplied with a small selection of “spare” button images. New button images can be created by editing the existing images or by drawing new images. To edit a button image: 1. Choose Tools Ö Customize. 2. Right-click the button image to be edited and choose Edit Button Image.

© Premier Training Limited

Page 16

Excel 2007 VBA

3. To edit the existing image, select a colour and fill the pixels of the image. 4. To draw a new button image, choose the Clear button and then follow step 3. Images can also be copied and pasted from other buttons or graphics applications.

Changing a Button’s ScreenTip By default, a new custom button is given the name “&Custom Button”. The name of the button appears as the button’s ScreenTip when the mouse is positioned over it. To change a button’s ScreenTip: 1. Choose Tools Ö Customize. 2. Right-click the button image to be edited and type the button’s name in the Name box.

Relative References If the relative reference option is not chosen the macro records the actual cell references and will always operate on those fixed cells, regardless of which cell is active when the macro is initiated. The following macro selects the range B3 to C5: Sub SelectAbsolute() Range("B3:C5").Select

© Premier Training Limited

Page 17

Excel 2007 VBA End Sub If a macro is recorded using relative references, cell references are recorded relative to the previously active cell. The macro then operates on cells relative to the cell that is active when the macro is initiated. The following macro selects a single cell, one row beneath the starting cell: Sub SelectRelative() ActiveCell.Offset(1, 0).Range("A1").Select End Sub •

To set the reference type:

When recording a macro, click the Relative References button on the Stop Recording toolbar. By default, Excel records in absolute mode. Recording can be switched from absolute to relative, and vice versa, during the same recording process. See also The Range Object page Error! Bookmark not defined..

Editing A Macro You can use ALT + F11 to enter the Visual Basic Code Editor… Entering and editing the text in a VBA module works just as you would expect. You can select text and copy it as you would in any Microsoft Application. A single instruction can be as long as you require it to be, however for readability, it’s easier to read if you break it onto two or more lines. To do this, end the line with a space followed with and underscore, continuing the code on the next line e.g. Msgbox (“The name entered into the Cell A1 on Worksheet 1 _ was “ & MyName)

As you enter code in the VB editor, you’ll notice that Excel makes some adjustments to your text, for example, if you omit the space before or after the equals sign (=), Excel enters it for you. Also various words in your code will become Title case. This is normal and will assist you in your code later

© Premier Training Limited

Page 18

Excel 2007 VBA on. Auto Indent Option (Tools-Options) The Auto Indent Option setting determines whether VBA automatically indents each new line of code by the same amount as the previous line. You can specify the number of characters, the default is four. Don’t use the space bar to indent your code, use the Tab key. This also works if you select more that one line of code.

Like Excel the VB Editor has many levels of Undo and Redo.

© Premier Training Limited

Page 19

Excel 2007 VBA

Exercise 1 1. Record a macro named SystemDate to enter the system date in the active cell, format it to a suitable date format, change the font to Arial 10 and AutoFit the column width. 2. Edit the SystemDate macro to include better use of the With statement.

© Premier Training Limited

Page 20

Excel 2007 VBA

Exercise 2 1. Record the command Edit Ö Clear Ö Formats as a macro named “ClearFormat” to clear the formatting from a selection of cells. Assign the macro to the shortcut key combination [CTRL]+[SHIFT]+[f]. Assign the macro to a custom button on a customised toolbar. Assign the macro to a button on a worksheet. 2. Record a macro named “Address” to enter the first three lines of an address in consecutive cells in a column. Record the macro using relative cell references. 3. Save the workbook containing the macros as EXERCISE 1.XLS.

© Premier Training Limited

Page 21

Excel 2007 VBA

Answers to Exercise 1

Question 1 Sub SystemDate() ActiveCell.FormulaR1C1 = "=NOW()" With Selection.Font .Name = "Arial" .FontStyle = "Regular" .Size = 10 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlNone .ColorIndex = xlAutomatic End With Selection.NumberFormat = "dd-mmm-yy" Selection.EntireColumn.AutoFit End Sub

Question 2 Sub SystemDate() ActiveCell.Formula = "=NOW()" With Selection With .Font .Name = "Arial" .Size = 10 End With .NumberFormat = "dd-mmm-yy" .EntireColumn.AutoFit End With End Sub

© Premier Training Limited

Page 22

Excel 2007 VBA

Answers to Exercise 2 Question 1 Sub ClearFormat() Selection.ClearFormats End Sub

Question 2 Sub Address() ActiveCell.FormulaR1C1 = "XYZ Company" ActiveCell.Offset(1, 0).Range("A1").Select ActiveCell.FormulaR1C1 = "Any Street" ActiveCell.Offset(1, 0).Range("A1").Select ActiveCell.FormulaR1C1 = "Any Town" End Sub

© Premier Training Limited

Page 23

Excel 2007 VBA

Module 3 - Overview of Visual Basic Editor Visual Basic Editor Excel is supplied with the Visual Basic Editor for modifying and creating macros and for creating user defined forms. The Visual Basic Editor is common to all the Microsoft Office 97 applications. To start with, the Visual Basic Editor contains two important windows: the Project Explorer and the Code window.

Creating Modules Standard Code Modules, also called simply Code Modules or just Modules, are where you put most of your VBA code. Your basic macros and your custom function (User Defined Functions) should be in these modules. Your workbook's VBA Project can contain as many standard code modules as you want. This makes it easy to split your procedure into different modules for organization and ease of maintenance. Workbook And Sheet Modules are special modules tied

© Premier Training Limited

Page 24

Excel 2007 VBA directly to the Workbook object and to each Sheet object. The module for the workbook is called ThisWorkbook, and each Sheet module has the same name as the sheet that it is part of. These modules should contain the event procedures for the object, and that's all. User Form Modules are part of the UserForm object, and contain the event procedures for the controls on that form. For example, the Click event for a command button on a UserForm is stored in that UserForm's code module. Like workbook and sheet modules, you should put only event procedures for the UserForm controls in this module. Class Modules are used to create new objects.

VBA Modules VBA Modules are stored in an Excel Workbook, but you view or edit a module using the Visual Basic Editor. A VBA Module consists of Procedures. A Procedure is a unit of code that performs some action. Below is an example of a Sub Procedure, Sub Example() Answer = 1+1 MgsBox “The result is “ & Answer End Sub A VBA module can also have Function procedures.

Function Procedures

Introduction There are in excess of 300 functions available in formulae on an Excel worksheet, such as SUM, IF and AVERAGE. These functions can be entered into cells directly or via the Function Wizard. Visual Basic also contains functions. Some Visual Basic functions are similar to worksheet functions such as, NOW and YEAR, others are standard to all forms of the BASIC

© Premier Training Limited

Page 25

Excel 2007 VBA language and some are unique to Visual Basic. Despite the number and complexity of functions available there is often a need to create others. A user-defined function can be used on a worksheet or in a module. A userdefined function can be thought of as a “stored formula”.

User-Defined Functions Function procedures return a value. A function procedure is enclosed by Function and End Function statements and must contain a statement that will return a value to the place where the function was called. Functions usually have data passed to them, this is specified in brackets after the function name. Function Function1 (variable list) Commands Function1 = Expression End Function A function procedure can be used as a user-defined function provided it does not perform actions that alter the Excel environment for example inserting, deleting or formatting cells; moving, adding or deleting sheets. Functions can only return values, they can not perform actions with objects. User-defined functions allow the user to type the procedure name directly into a cell on the worksheet, followed by the required data enclosed in brackets and separated by commas in the order expected by the function procedure. In the following example, the function Percentage is expecting two variables to be passed. It uses the variables to calculate the percentage and the result is passed back: Function Percentage (Amount, Percent) ‘Increase amount by percent Percentage = (Amount*Percent/100)+Amount ‘Returns the result End Function To use the function in the worksheet, type the function name followed by the data that is to go into the variables enclosed in parenthesis: =Percentage (150,17.5) =Percentage (B1,B2) In the following example, the function Age is expecting one variable to be passed. It uses the variable to calculate the © Premier Training Limited

Page 26

Excel 2007 VBA age and the result is passed back: Function Age(DOB) If Month(DOB) > Month(Now) Then Age = Year(Now) - Year(DOB) - 1 ElseIf Month(DOB) < Month(Now) Then Age = Year(Now) - Year(DOB) ElseIf Day(DOB)