Professional Documents
Culture Documents
IMPORTANT NOTE
Unless otherwise stated, screenshots in this lesson were taken using Excel 2007 running
on Window XP Professional. There may be, therefore, minor differences in the
appearance and layout of dialog boxes and screens if you are using other Excel versions,
or if you are running on Windows 2000 or Windows Vista.
Contents
CONTENTS ............................................................................................................................................................. 3
REVIEW EXERCISE ................................................................................................................................................... 5
Automating a Worksheet Using VBA Basics......................................................................................................... 5
LESSON 1 - EXPLORING THE RANGE OBJECT............................................................................................... 6
REFERRING TO A RANGE ......................................................................................................................................... 7
COLLECTIONS ........................................................................................................................................................10
THE CURRENTREGION PROPERTY .........................................................................................................................12
THE OFFSET & RESIZE PROPERTIES ........................................................................................................................14
EXERCISE ...............................................................................................................................................................18
Working with the Range Object ..........................................................................................................................18
LESSON 2 - VARIABLES, CONSTANTS AND ARRAYS ...............................................................................19
DECLARING VARIABLES.........................................................................................................................................20
SCOPE AND VISIBILITY ...........................................................................................................................................21
CONSTANTS...........................................................................................................................................................22
ARRAYS .................................................................................................................................................................24
DECLARING AN ARRAY ..........................................................................................................................................24
ARRAY TYPES .........................................................................................................................................................26
ASSIGNING VALUES TO AN ARRAY .........................................................................................................................31
FILLING ARRAYS USING LOOPS .............................................................................................................................33
DYNAMIC ARRAYS .................................................................................................................................................35
THE ARRAY FUNCTION .........................................................................................................................................38
EXERCISE ...............................................................................................................................................................41
Variables and Arrays .........................................................................................................................................41
LESSON 3 - USER DEFINED FUNCTIONS .......................................................................................................43
USING EXCEL WORKSHEET FUNCTIONS IN VBA ...................................................................................................44
VBA FUNCTIONS ...................................................................................................................................................46
USER-DEFINED FUNCTIONS ...................................................................................................................................49
GETTING HELP WITH USER DEFINED FUNCTIONS ..................................................................................................52
DECLARING VARIABLES IN USER DEFINED FUNCTIONS .........................................................................................54
USING RANGES IN USER DEFINED FUNCTIONS ......................................................................................................55
EXERCISES .............................................................................................................................................................57
User Defined Functions .....................................................................................................................................57
LESSON 4 - ADD-IN APPLICATIONS ...............................................................................................................59
DEFINING AN ADD-IN ...........................................................................................................................................60
CREATING AN ADD-IN FOR USER DEFINED FUNCTIONS ........................................................................................61
INSTALLING AN ADD-IN ........................................................................................................................................63
EDITING AN ADD-IN .............................................................................................................................................64
REMOVING AN ADD-IN .........................................................................................................................................65
EXERCISE ...............................................................................................................................................................67
Working with an Add-In .....................................................................................................................................67
LESSON 5 TESTING AND DEBUGGING CODE ..........................................................................................68
TYPES OF ERROR AND DEBUGGING ........................................................................................................................69
STEPPING THROUGH A PROCEDURE ......................................................................................................................70
DISPLAYING VARIABLE VALUES ............................................................................................................................73
BREAK MODE ........................................................................................................................................................76
EXERCISE ...............................................................................................................................................................81
Testing and Debugging Code .............................................................................................................................81
Excel Level 6: VBA Intermediate) Contents
Excel Level 6: VBA Intermediate) Review Exercise
REVIEW EXERCISE
AUTOMATING A WORKSHEET USING VBA BASICS
2. Launch the VBA Editor and open the module sheet in the Daily Profit and Loss project
containing the CreateTable procedure.
4. Create a button on Sheet1 of the workbook and assign the CreateTable macro to it.
5. Use this button to run the macro and check that it runs correctly. It should result in
the following.
Edit the procedure with a loop so that after it tests cell B4, it also tests cell C4.
9. Assign a keystroke of your choice to this macro and run it to check that it works
correctly. The font in cell B4 should be made red and the font in cell C4 bold.
10. Put right any errors and then save and close the file.
LESSON 1 - EXPLORING THE RANGE OBJECT
In this lesson, you will learn how to:
Refer to ranges
Use collections
REFERRING TO A RANGE
Discussion
Procedures will almost certainly need to work with ranges; these ranges will usually
differ in size and position in a workbook and hence, there needs to be flexible ways of
identifying and selecting them.
Range(reference)
eg. Range(A1)
Range(B2 : D10)
An alternative way of selecting a range of cells that can provide more flexibility, is to
separate the first cell from the last one with a comma, eg.
Range("A1", "A10")
Several (non contiguous) ranges can be referred to by typing them into the Range
argument with commas separating them and quote marks () at the beginning and
end, eg.
Range("A1", "A10").Interior.ColorIndex = 15
(add a light grey fill colour to the range A1 : A10)
Cells(1) or Cells(1, 1)
Cells(1) identifies it as cell number 1 of the worksheet, ie. A1. The Index counts along
the row before returning to the beginning of the next row and resuming from where
it left off. B1, therefore, would be Cells(2), C1 would be Cells(3)... etc.
In Excel 2000 03, the last cell in row 1 (IV1) would be referred to with an index of
256 - Cells(256). A2 would then have the index 257 - Cells(257).
In Excel 2007, however, there are 16,384 columns (unless you are running it in
compatibility mode). The last cell in row 1 (XFD1), therefore, would be Cells(16384)
and A2 would be Cells(16385).
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
It makes things easier, therefore, the use the cells property with TWO index numbers,
the first being the row number and the second the column number. For example, A2
can be referred to as:
Cells(1, 1) - the cell that is in row 1 and column 1 of the worksheet (A1).
Cells(2, 1) - the cell that is in row 2 and column 1 of the worksheet (A2)
Cells can also be used on its own as a collection (see page 10). It would then refer to
ALL the cells on a worksheet or a selection, eg.
Sheets(Sheet2).Cells.Font.Name = Calibri
numCels = Selection.Cells.Count
The Cells property is generally more powerful and flexible than the Range property,
although Range is still best used when referring to specific (absolute) cells or ranges.
The Cells property and the Range property can be used together as follows:
This refers to the range A1 : C3, Cells(1, 1) being A1 and Cells(3, 3) being C3.
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
COLLECTIONS
Discussion
It was explained in the previous topic that Cells may be used on its own to represent
a collection. Relevant methods and properties can then be applied to a whole
collection (or type) of object. For example:
Cells.Select
To identify and refer to a single item in a collection, you normally have to refer to it
by its index number, or by its name (as a string). For example:
WorkBooks(1) is the first workbook opened (assuming that several are open).
WorkBooks(Sales Data.xls) is specifically the open file named Sales Data.
Sheets(1) is the first sheet from the left of the workbook.
Sheets(January) is specifically the sheet named January.
Rows(1) refers to row 1 of the active worksheet.
Columns(1) is the same as Columns(A) and refers to column A of the active
worksheet.
To select a range of columns, for example from B through G, would require the code
Columns(B : G).Select. This is the only way to specify a range of columns within a
collection, numbers (eg. Columns(2 : 7) are not allowed.
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor in the procedure where you want to
write the code.
5. Type the object that you want to refer to.
6. Type a full stop.
7. Type the method or property that you want to apply to
the object.
8. Press Enter.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
To achieve this, CurrentRegion needs a starting point (an expression that returns a
range object). The starting point can be any cell on the range. The syntax is:
<expression>.CurrentRegion.<method or property>
In the picture above, the code for selecting the contiguous range A3 to B22 might be:
Range(A3).CurrentRegion.Select
If a cell is already active on the range, the code could be written as follows:
ActiveCell.CurrentRegion.Select
For example:
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
Range(A1 : G200).Select
Selection.Copy Destination:= Sheets(1).Range(A2)
... will always select the cells from A1 to G200, copy
them and paste them into cell A2 on the second sheet of
the workbook.
Nevertheless, if you want to run the same procedure on a different table that does not
span from cells A1 to G200, then the procedure will not work correctly. Using the
CurrentRegion property, however, it would be successful, eg.
ActiveCell.CurrentRegion.Select
Selection.Copy Destination:= Sheets(1).Range(A2)
The example above would require a cell to be selected on the table first, but would
succeed a table containing any number of rows and columns anywhere on the
worksheet.
Another useful way of selecting cells CurrentRegion would be to use arguments for
it. The following example would select the cell 2 Rows down and 2 Columns to the
right, from the first cell in the current region.
ActiveCell.CurrentRegion(2, 2).Select
An alternative method would be to use the activate method. This would be useful if
the current region was selected first and needed to be kept selected. Using activate
will make a cell active without removing any cell selection.
ActiveCell.CurrentRegion.Select
ActiveCell.CurrentRegion(3, 6).Activate
CurrentRegion(2, 2).Activate
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor in the procedure where you want to
write the code.
5. Type the object that you want to refer to.
6. Type a full stop.
7. Type the method or property that you want to apply to
the object.
8. Press Enter.
Offset
The Offset property is discussed in the Excel VBA Introduction booklet with respect
to it identifying a single cell that is away from another one (see Excel VBA
Introduction (Student Edition), page 63) . For example:
ActiveCell.Offset(1,0).Select
... would select the cell that is 1 row and 0 columns away
from the active cell. If the active cell was B10, therefore,
Offset(1,0) would refer to B11 (one row down, same
column).
The Offset property can also be used to offset an entire range of cells.
The following example moves a selected range 1 cell down and 1 column to the right:
Range(A1).CurrentRegion.Select
Selection.Offset(1,1).Select
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
Range(A1).CurrentRegion.Select Selection.Offset(1,1).Select
This proves useful where a table has to be selected excluding the top row and left
column.
Resize
Using the Resize function enables a selected range of cells to be made bigger or
smaller by increasing or decreasing the number of rows and columns that it contains.
The new size of the range is measured from its top left corner. In the example
below, a current region is selected and then resized to 15 rows and 4 columns.
ActiveCell.CurrentRegion.Select
Selection.Resize(15, 4).Select
The Resize property proves useful where a table has to be selected excluding the
bottom row and right column. To achieve this, VBA has to do a bit of work for you! It
has to count the number of rows and columns in the table so that a calculation can be
performed to determine how many rows and columns to resize the table to.
The example below uses variables to count the number of rows and columns in a
table (the selection), and then adds 1 to determine the resize parameters:
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
ActiveCell.CurrentRegion.Select
numRows = Selection.Rows.Count + 1
numCols = Selection.Columns.Count + 1
Selection.Resize(numRows, numCols).Select
numRows = Selection.Rows.Count + 1
= 20 + 1 = 21
numCols = Selection.Columns.Count + 1
=5+1=6
ActiveCell.CurrentRegion.Select
Selection.Resize(numRows,numCols).Select
The example above could also be written without the use of variables, although this
may make the code more complicated to write and understand:
ActiveCell.CurrentRegion.Select
Selection.Resize(Selection.Rows.Count + 1, Selection.Columns.Count + 1).Select
The Offset and Resize properties work well together as in the following example. A
range is offset by 1 row and 1 column and then resized to 1 row and 1 column less, so
that it excludes the blank row and blank column at the bottom and right.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
ActiveCell.CurrentRegion.Select
numRows = Selection.Rows.Count -1
numCols = Selection.Columns.Count -1
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor in the procedure where you want to
write the code.
5. Type the object that you want to refer to.
6. Type a full stop.
7. Type the method or property that you want to apply to
the object.
8. Press Enter.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
EXERCISE
WORKING WITH THE RANGE OBJECT
1. Insert a new module in your Personal Macro Workbook and write a sub procedure
named, LayoutTable that:
a. selects a whole table of data;
b. adjusts the width of all the columns to 12pts;
c. formats the font colour of the first column to blue;
d. aligns the text centrally in the first row.
2. Assign this macro to a custom button on your My Macros toolbar.
3. Open the file, Ranges.
4. Run and test LayoutTable on the table in Sheet1 of this workbook.
5. Write another sub procedure in your Personal Macro Workbook named,
FormatNumbers that selects a whole table excluding the top row and the left-
most column and formats it to a currency style.
6. Assign this macro to a custom button on your My Macros toolbar.
7. Run and test FormatNumbers on the table in Sheet 1 of this workbook.
8. Create a final sub procedure in your Personal Macro Workbook named, LastCell
that selects the last cell of a table (the one in the bottom right-hand corner) and:
a. makes the font size 14pts;
b. adds a yellow fill colour; and
c. autofit the column.
9. Assign this macro to a custom button on your My Macros toolbar.
10. Run and test LastCell on the table in Sheet 1 of this workbook.
11. Create a new sub procedure in your Personal Macro Workbook named,
RunAllMacros.
12. Call into this sub procedure the three macros created above.
13. Assign this macro to a custom button on your My Macros toolbar.
14. Run and test RunAllMacros on the table in Sheet2 of this workbook.
15. Save and close the file.
16. Exit Excel to ensure that the Personal Macro Workbook is saved.
17. Re-launch Excel.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
LESSON 2 -
VARIABLES, CONSTANTS AND ARRAYS
In this lesson, you will learn how to:
Declare Variables
Define Constants
Declare Arrays
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
DECLARING VARIABLES
Discussion
Variables that are to be used in a procedure are usually declared at the start of that
procedure in order to identify them and the type of data that they will hold.
In VBA, it is not necessary to declare variables, but by doing so, it is possible to speed
up the procedure, conserve memory and prevent errors from occurring.
Because variables do not have to be declared Visual Basic assumes any variable that
has not yet been used to be a new variable. This means a variable spelled incorrectly
during code writing would not be recognised by Visual Basic.
This problem can be avoided by choosing to declare explicitly every variable. This
tells Visual Basic that every variable will be declared in advance and any others used,
misspelt or not, will be incorrect. When Visual Basic encounters an undeclared
variable, the following message is displayed:
To explicitly declare variables, the following statement is required at the top of the
Visual Basic module:
Option Explicit
Variables are then declared by using the Dim Statement.
Dim variable name
The variable exists until the end of the procedure is met.
The Option Explicit Statement can be set automatically to appear in all modules.
Procedures
1. In the Visual Basic Editor, Select Tools... Options.
2. Select the Editor Tab.
3. Select Require Variable Declaration.
4. Click on the OK button.
Procedures
1. Launch or switch to the VB Editor.
2. Identify the workbook (VBA project) to which you want
to add code in the Project Explorer pane.
3. Open the module sheet containing the code or, insert a
new module.
4. To declare a variable at module level, position the
cursor at the very top of the module sheet and type Dim.
To declare a public, variable, position the cursor at the
very top of the module sheet and type Public.
5. Type a space.
6. Type the name for the variable.
7. Type a space.
8. Type As.
9. Type a space.
10. Type or select from the list and appropriate data type for
the variable.
11. Press Enter.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
CONSTANTS
Discussion
A constant is a named item that retains a constant value throughout the execution of
a program, as opposed to a variable, whose value may change during execution.
By storing a value as a constant, it indicates to anyone reading or having to edit the
procedure, that wherever you see the constant being used, its value will always be as
assigned in the Const statement. Like many things in programming, it is an example
of good practice and intended to keep the code neat, concise and easily understood.
Constants are defined using the Const statement. Constants can be used anywhere in
a procedures in place of actual values. A constant may be a string or numeric literal,
another constant, or any combination that includes arithmetic or logical operators
except Is. For example:
Sub Font_Colour()
Const RED = 3
Const BLUE = 5
Const YELLOW = 6
Selection.Font.ColorIndex = RED
Selection.Interior.ColorIndex = YELLOW
Selection.BorderAround ColorIndex:= BLUE
End Sub
Like variables, constants should be declared in order to inform, prevent errors and
manage computer memory. Constants are not, however, "dimmed" in the same way
as variables. They are declared as type immediately after the name of the constant. In
the example below, a constant has been created to store the value of pi ().
Procedures
1. Launch or switch to the VB Editor.
2. Identify the workbook (VBA project) to which you want
to add code in the Project Explorer pane.
3. Open the module sheet containing the code or, insert a
new module.
4. Identify the procedure that you wish to declare the
constant in or, start typing a new procedure.
5. Position the cursor immediately below the Sub statement
at the top of the procedure.
6. Type Const.
7. Type a space.
8. Type a name for the constant. Tip: constant names are
normally written all UPPER CASE.
9. Type a space.
10. Type As.
11. Type or select from the list a data type for the variable.
12. Type a space.
13. Type =.
14. Type a value for the constant.
15. Press Enter.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
ARRAYS
Discussion
An array is a special type of variable that can contain many
"elements" of information simultaneously - in essence a large
variable. Think of it as a box containing many separate sections,
rather like pigeon holes in a post room.
An array stores large numbers of values more efficiently that using an equivalent
numbers of individual variables. Not only does an array make better use of computer
memory, but it can be "filled" extremely quickly and flexibly with a minimum
amount of code. Storing a column of 100 numbers in individual variables would take
100 lines of code. With an array, it can be done with just three!
DECLARING AN ARRAY
Discussion
An array must be declared before it can be used. Like a variable, it is declared with a
Dim statement, followed by the name of the array. What makes an array different is
that after the name, there are brackets containing a number (or numbers). This
number (or numbers) denote how many elements the array contains. This is referred
to as the dimension of the array. For example, the following example declares an array
containing 5 elements:
You may now be asking the question: "Why 4 when the array must contain 5
elements?"
The number 4 is used because it is the upper bound of the array that is used in the
brackets, NOT the number of elements required. Because the lower bound is 0, an
upper bound of 4 does, therefore, indicate that the array contains 5 elements.
The same data types as for variables can be used. These are given in the table below:
Data type Memory size Storage capability
Byte 1 byte 0 to 255
Boolean 2 bytes True or False
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,647
Single 4 bytes -3.402823E38 to -1.401298E-45 for negative values;
1.401298E-45 to 3.402823E38 for positive values
Double 8 bytes -1.79769313486231E308 to
-4.94065645841247E-324 for negative values;
4.94065645841247E-324 to 1.79769313486232E308
for positive values
Currency 8 bytes -922,337,203,685,477.5808 to
922,337,203,685,477.5807
Decimal 14 bytes +/-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
Date 8 bytes January 1, 100 to December 31, 9999
String 10 bytes + 0 to approximately 2 billion
(variable- string length
length)
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
Procedures
1. Launch or switch to the VB Editor.
2. Identify the workbook (VBA project) to which you want
to add code in the Project Explorer pane.
3. Open the module sheet containing the code or, insert a
new module.
4. Identify the procedure that you wish to declare the array
in or, start typing a new procedure.
5. Position the cursor immediately below the Sub statement
at the top of the procedure.
6. Type Dim.
7. Type space.
8. Type a name for the array.
9. Type a space.
10. Type an opening bracket (.
11. Type the upper bound for the array, (this will be a single
number).
12. Type a closing bracket ).
13. Type a space.
14. Type As.
15. Type or select from the list an appropriate data type for
the array.
16. Press Enter.
ARRAY TYPES
Discussion
If you wish ALL arrays on a module sheet to use 1 as the lower index, you can type
the words:
Option Base 1
The Option Base 1 statement at the top of the module sheet indicates that the lower
bound is 1. The following extract from the VB Editor clarified the code.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
Procedures
1. Launch or switch to the VB Editor.
2. Identify the workbook (VBA project) to which you want
to add code in the Project Explorer pane.
3. Open the module sheet containing the code or, insert a
new module.
4. Identify the procedure that you wish to declare the array
in or, start typing a new procedure.
5. Position the cursor immediately below the Sub statement
at the top of the procedure.
6. Type Dim.
7. Type space.
8. Type a name for the array.
9. Type a space.
10. Type an opening bracket (.
11. Type the lower bound (this will be a single number).
12. Type a space.
13. Type To.
14. Type the upper bound (this will be a single number)
15. Type a closing bracket ).
16. Type a space.
17. Type As.
18. Type or select from the list an appropriate data type for
the array.
19. Press Enter.
Multi-dimensional arrays
The arrays described in the previous topics are one-dimensional arrays. A useful
analogy is to imagine the elements in one single row.
Arrays can have up to 60 dimensions, although 1, 2 or 3 are normally used. A 2-
dimensional array, for example, is useful for storing values from a worksheet that are
in columns and rows.
A 2-dimensional array is created by declaring it as follows:
Any of the above would create an array that is 4 elements tall and 3 elements wide.
The example below fills the array with values from the range A1 to C4.
arrData(1, 1) = Range("A1").Value
arrData(1, 2) = Range("B1").Value
arrData(1, 3) = Range("C1").Value
arrData(2, 1) = Range("A2").Value
arrData(2, 2) = Range("B2").Value
arrData(2, 3) = Range("C2").Value
arrData(3, 1) = Range("A3").Value
arrData(3, 2) = Range("B3").Value
arrData(3, 3) = Range("C3").Value
arrData(4, 1) = Range("A4").Value
arrData(4, 2) = Range("B4").Value
arrData(4, 3) = Range("C4").Value
Think of this array as a cube that has depth as well as height and
width.
3
3 3
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
To use this array to store values, you would need to refer to all three dimensions, for
example:
ArrData(1 , 1 , 1) = ...
ArrData(1 , 1 , 2) = ...
ArrData(1 , 1 , 3) = ...
ArrData(1 , 1 , 4) = ...
ArrData(1 , 2 , 1) = ...
ArrData(1 , 2 , 2) = ...
ArrData(1 , 2 , 3) = ...
ArrData(1 , 2 , 4) = ...
ArrData(2, 1 , 1) = ...
ArrData(2, 1 , 2) = ...
........etc.
Procedures
1. Launch or switch to the VB Editor.
2. Identify the workbook (VBA project) to which you want
to add code in the Project Explorer pane.
3. Open the module sheet containing the code or, insert a
new module.
4. Identify the procedure that you wish to declare the
multidimensional array in or, start typing a new
procedure.
5. Position the cursor immediately below the Sub statement
at the top of the procedure.
6. Type Dim.
7. Type a space.
8. Type a name for the array.
9. Type a space.
10. Type an opening bracket (.
11. Type the upper bound of the first dimension of the array
(this will be a single number).
12. Type a comma .
13. Type the upper bound of the second dimension of the
array (this will be a single number)
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
Floor (6)
Floor (5)
Floor (4)
Floor (3)
Floor (2)
Floor (1)
Floor (0)
Note that the lowest element is not referred to as floor (1) but floor (0). By default,
arrays number their elements starting with 0 NOT 1. The lowest index of an array
(usually number 0) is known as the lower bound. The highest index of the array is
known as the upper bound.
As with a variable, creating an array starts with giving it a name. The naming rules
for variables apply equally to arrays and are given below:
Single characters (eg. a, b, c, x, y, z) should be avoided unless the array if being
used for simple counting purposes. Using this type of name can cause
ambiguity and it is better to use descriptive, but concise, names for your array,
eg: newnames, salesfigs, startdates, numcells.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
An array name must start with a letter and not a number. Numbers can be
included within the name, but not as the first character, eg. salesfigs1 but not
1salesfigs.
The first character of an array name should be left lowercase. Because VBA
words always start with an uppercase character (eg. ActiveCell, WorkBook,
Cells, etc), keeping the first character lowercase helps make your arrays (like
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 array names. You can separate words by either
capitalisation, eg. newNames, or by using the underscore character, eg.
new_names.
Most punctuation marks (eg. , . : ; ? -) and special characters (eg. $, %, ^, &, #,
}) cannot be used.
An array name can be no longer than 250 characters.
The example below shows how to create an array named arrData that stores the
values in the range B11:B16 in its elements numbered from 0 to 5.
arrData(0) = Range("B11").Value
arrData(1) = Range("B12").Value
arrData(2) = Range("B13").Value
arrData(3) = Range("B14").Value
arrData(4) = Range("B15").Value
arrData(5) = Range("B16").Value
arrData(0) through to arrData(5) can be used like normal variables. The following
example returns the contents of the above array into the range(D10:D15) of Sheet2.
Sheets("Sheet2").Range("D10").Value = arrData(0)
Sheets("Sheet2").Range("D11").Value = arrData(1)
Sheets("Sheet2").Range("D12").Value = arrData(2)
Sheets("Sheet2").Range("D13").Value = arrData(3)
Sheets("Sheet2").Range("D14").Value = arrData(4)
Sheets("Sheet2").Range("D15").Value = arrData(5)
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
Procedures
1. Launch or switch to the VB Editor.
2. Identify the workbook (VBA project) to which you want
to add code in the Project Explorer pane.
3. Open the module sheet containing the code or, insert a
new module.
4. Identify the procedure that you wish to declare the
constant in or, start typing a new procedure.
5. Position the cursor in the procedure where you want to
assign values to the array.
6. Type the name of the array.
7. Type an opening bracket (.
8. Type the index number of the array element where you
want to store the value (this will be a single number).
9. Type a closing bracket ).
10. Type a space.
11. Type =.
12. Type a space.
13. Type the value that you want to store.
14. Press Enter.
The following example uses a nested For... Next loop to fill a 2-dimensional array
with values from the range A1 to C3.
For i = 1 To 3
For j = 1 To 4
arrData(i, j) = Cells(i, j).Value
Next j
Next i
Procedures
1. Launch or switch to the VB Editor.
2. Identify the workbook (VBA project) to which you want
to add code in the Project Explorer pane.
3. Open the module sheet containing the code or, insert a
new module.
4. Identify the procedure that you wish to declare the
constant in or, start typing a new procedure.
5. Position the cursor in the procedure where you want to
assign values to the array.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
6. Type For.
7. Type a space.
8. Type a variable name for the For loop (eg. i).
9. Type =.
10. Type the lower bound of the array that you want the loop
to fill.
11. Type a space.
12. Type To.
13. Type a space.
14. Type the upper bound of the array that you want the
loop to fill.
15. Press Enter.
16. Type the name of the array.
17. Type an opening bracket (.
18. Type the variable name that you have used for the loop.
19. Type a closing bracket ).
20. Type a space.
21. Type =.
22. Type a space.
23. Type the value that you want to store.
24. Press Enter.
25. Type Next.
26. Type a space.
27. Type the variable name for the loop.
28. Press Enter.
DYNAMIC ARRAYS
Discussion
In earlier examples, we have known what size to make the array in advance, and
hence, been able to create the appropriate number of elements and/or dimensions.
This is known as a fixed-size array.
Sometimes, you may not know how many elements you need in an array until it has
been calculated out, usually in the form on a variable. In these cases, you declare a
dynamic array by creating a name for the array, adding brackets but leaving them
empty, eg.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
Dim arrData() As Type
Once the number of elements and dimensions for the array have been determined, it
can be declared again but using the Redim statement. In the following example, a
dynamic array is declared at the beginning of the sub procedure. The number of
elements required is then calculated out and the array is redimensioned to the correct
size.
Dim arrData()
(declares the dynamic array)
numCels = Selection.Cells.Count
(counts the number of cells in a selected area of the worksheet)
A dynamic array can be redimensioned as many times as necessary, but you cannot
change its data type from how you originally declared it. For example, the code
below would give an error message:
var1 = Selection.Cells.Count
(calculate size of array)
Error Message
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
If all the elements in a dynamic array have been filled with values, and you need to
make it bigger, you can redim it again. Beware, however, that you may lose all the
original values in it. To avoid this happening you must use the Preserve keyword
after ReDim.
In the example below, the dynamic, 1-dimensional array arrData(1 To 4) has been
already been filled with values. It is then redimmed to make it bigger by two extra
elements (1 To 5). The keyword Preserve is used in the ReDim statement so that the
values in (1 To 3) are not lost.
ReDim arrData (1 To 3)
(redimension array to contain 3 elements)
arrData(1) = "Tom"
arrData(2) = "Harry"
arrData(3) = "Joe"
(fill array)
If Preserve had not been used, arrData(4) and arrData(5) would have successfully
stored Sally and Jane, but Tom, Harry and Joe would have been lost from arrData(1),
(2) and (3).
Procedures
1. Launch or switch to the VB Editor.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
As for arrays in general, the name of the array followed by the required element
index number in brackets, eg.
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor immediately below the Sub statement
at the top of the procedure.
5. Type Dim.
6. Type a space.
7. Type a name for the array.
8. Type a space.
9. Type As.
10. Type a space.
11. Type Variant.
12. Press Enter.
Excel Level 6: VBA Intermediate) Variables, Constants and Arrays
EXERCISE
VARIABLES AND ARRAYS
Task 1: Write a procedure that prompts the user to enter data, using variables and arrays.
1. Open the file Forecast. This workbook already contains a macro named
CreateNewForecast that makes a copy of the sheet - Template - at the end
of the workbook.
2. Add to this sub procedure, VBA code that:
a. prompts the user by means of an Input Box, for a month name to give
to the sheet. This value must be stored in a locally declared variable,
and then used to rename the sheet.
b. prompts the user by means of four Input Boxes, for some values to
enter into cells B2, C2, D2 and E2. These values should be stored in a
locally declared, 1-dimensional array and then entered into the
appropriate cells.
(Tip: Try using FOR NEXT loops for this purpose)
3. Assign the sub procedure to a worksheet button on the Template sheet and
then run and test it using some made-up data of your own. Correct code if
necessary.
4. Save and close the file.
Name Argument
Name Arguments
1,2,3
You can use many built-in Excel functions in sub procedures. In Excel 2007, the
number is approximately 280, but earlier versions had significantly less. The syntax is
as follows:
To help you indentify available functions, the Auto Members List displays a list of
them after typing the dot (.) following WorksheetFunction.
The following statement returns into cell G10, the sum of the values in cells G2 to G9.
Range(G10).Value = Application.WorkSheetFunction.Sum(Range(G2:G9))
Excel Level 6: VBA Intermediate) Function Procedures
Note that the argument for the Sum function is not expressed in the usual Excel way,
(eg. G2:G9), but as a valid VBA reference to G2:G9, ie. Range(G2:G9).
Alternatively, Selection can be used as the argument. The following example selects
the range G2:G9 and returns the SUM result of the selection into cell G10.
Range(G2:G9).Select
Range(G10).Value = Application.WorkSheetFunction.Sum(Selection)
Range(G10).Formula = Application.Sum(Range(G2:G9))
Note that both examples above do NOT write the actual formula into the cell. The
calculation is performed in the sub procedure, and the result only is returned to the
cell.
To show the SUM function in the cell, the following code has to be used:
Range(G10).Formula = =Sum(G2:G9)
This literally writes the formula into the cell as a string. Excel then takes over and
carries out the calculation.
For a full list of VBA functions (Excel 2003 but valid for other versions too) can be
found at the following Web address:
http://msdn.microsoft.com/en-us/library/aa221655(office.11).aspx
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor in the procedure where you want to
use the workbook function.
5. Type the object to which you want the worksheet
function to refer to, eg. ActiveCell
6. Type a full stop.
7. Type Value.
Excel Level 6: VBA Intermediate) Function Procedures
8. Type =.
9. Type Application
10. Type a full stop.
11. Type WorkSheetFunction.
12. Type a full stop.
13. Type the name of the function that you want to use or,
select it from the list.
14. Type an opening bracket (.
15. Type the argument(s) for the function (this has to be in a
VBA form, eg. Range(A1:A5) NOT A1:A5).
16. Type a closing bracket ).
17. Press Enter.
VBA FUNCTIONS
Discussion
In addition to the Excel worksheet functions, there are approximately 92 VBA
functions (in Excel 2007) that can be used in sub procedures. In many cases, they
perform equivalent calculations to the Excel worksheet functions, but in some cases
augment them.
In some cases, where there is a VBA function to carry out a calculation, the equivalent
Excel worksheet function cannot be used, and will not appear in the Auto Members
List following WorksheetFunction..
Examples of VBA functions that have equivalent Excel worksheet functions, but
which are not written the same are:
VBA Function Excel Worksheet Description
Equivalent
Date =TODAY() Returns the current system date.
Rnd =RAND() Returns a random number greater
than or equal to 0 and less than 1.
UCase(string) =UPPER(text) Converts text to upper case.
LCase(string) =LOWER(text) Converts text to lower case.
IsNumeric(expression) =ISNUMBER(value) Checks whether a value is a number
and return TRUE or FALSE
Examples of VBA functions that have equivalent Excel worksheet functions, and
which are written the same are:
Excel Level 6: VBA Intermediate) Function Procedures
VBA Function Excel Worksheet Description
Equivalent
Round(expression,digits) =ROUND(number,digits) Rounds a number to the closest
number of digits, eg.
=ROUND(34.567,1) displays
34.6. =ROUND(34567,-3)
displays 35000.
Int(expression) =INT(number) Returns the whole part of a
number only, eg. =INT(34.567)
displays 34 and discards the
decimals.
Abs(number) =ABS(number) Returns a number without its
sign (ie. a negative becomes a
positive; a positive remains a
positive).
Day(date) =DAY(serial number) Returns the day that a date
falls on.
Month(date) =MONTH(serial Returns the month that a date
number) falls on.
Year (date) =YEAR(serial number) Returns the year that a date
falls on.
Now =NOW() Return the current system date
AND time.
Pmt(rate,periods,pv) =PMT(rate,nper,pv) Calculates the repayments for
a loan.
Fv(rate,periods,payment) =FV(rate,nper,pmt) Calculates the future value of
an investment.
There follow some examples of how some of these VBA functions might be used:
Range(A1).Value = Date
(Displays the current date in cell A1. The date is linked to the system clock so will be
updated automatically.)
Note that functions existing in VBA only, can only be used to return a value in the
sub procedure that that they are used in. For example, if you type directly into the
cell of a worksheet:
...... you would get the #NAME? error. This is because although UCase works in a
VBA sub procedure, it is not recognised by Excel as a valid worksheet function. The
correct worksheet function to use is: = UPPER(text).
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor in the procedure where you want to
use the VBA function.
5. Type the object to which you want the function to refer,
eg. ActiveCell
6. Type a full stop.
7. Type Value.
8. Type =.
9. Type the VBA function name.
10. Type an opening bracket (.
11. Type the argument(s) for the function.
12. Type a closing bracket ).
13. Press Enter.
Excel Level 6: VBA Intermediate) Function Procedures
USER-DEFINED FUNCTIONS
Discussion
It was described above how built-in worksheet or VBA functions can be used in sub
procedures. There may be times, however, when none these functions meet your
needs or meet then just partly. This is when a user-defined function procedure may
have to be created.
Unlike a sub procedure, a function procedure only returns a value. It does NOT
move around a workbook selecting worksheets and cells, changing their properties
and applying methods to objects. Like the dozens of built-in Excel and VBA functions
(eg. SUM, COUNT, LOOKUP, IF, PMT, DATE, etc...), they merely carry out a
calculation and return the result, either into the cell that they have been typed into or
to the sub procedure that they are being used in.
A function procedure is enclosed by, Function and End Function statements.
The function procedure must have a name that is (usually) followed by arguments
inside brackets. The arguments are the variables (pieces of information) that the
function needs in order to calculate out and return a value.
The following example shows a function procedure that is designed to calculate out
Value Added Tax (at the time of writing this was 15%).
Function VAT(amount)
VAT = amount * 0.15
End Function
The function procedure name is VAT and it requires a single piece of information
(variable) to calculate out a value: amount.
The calculation that the function needs to perform to return a value for VAT is
expressed in the statement: VAT = amount * 0.15.
This function could be used directly in a cell on a worksheet or it could be used in a
sub procedure. The example below shows it being used on a worksheet. By typing in
=VAT followed by an opening bracket, the amount that you want to carry out the
VAT calculation on (in this case, cell D6) and a closing bracket, the result will be
returned to the cell that the function is being typed into upon pressing Enter.
Excel Level 6: VBA Intermediate) Function Procedures
The examples below shows it being used in the same way, but in a sub procedure:
Range("E6").Value = VAT(Range("D6"))
(This will return the result only of the function into cell E6, not the formula itself)
Range(E6).Formula = =VAT(Range(D6))
Or,
ActiveCell.Formula = =VAT(ActiveCell.Offset(0 , -1).Value)
(These will write the actual formula into cell E6)
More examples are given below using multiple arguments and more code that is
complex.
The following uses two arguments to calculate the difference in years and decimal
fractions of a year, between two dates. The two arguments are separated by a comma:
The following function return 10% of sales but only where the sales value is greater
than or equal to 30000.
Excel Level 6: VBA Intermediate) Function Procedures
Function COM(sales_value)
If sales_value >= 30000 Then
COM = sales_value * 0.1
Else
COM = 0
End If
End Function
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet or, insert a new module.
4. Position the cursor in the module where you want to
create the function procedure.
5. Type Function.
6. Type a space.
7. Type a name for the function.
8. Type an opening bracket (.
9. Type the variable name(s) for the function argument(s).
10. Type a closing bracket ).
11. Press Enter.
12. Type the necessary calculation(s) to return a value for the
function.
13. Type End Function
14. Press Enter.
Excel Level 6: VBA Intermediate) Function Procedures
The second way that you can get help with a user-defined function is by opening the
Insert Function window. This is available in all versions of Excel and offers help on
all Excel worksheet functions as well as any user defined ones available.
To find the user defined functions, you have to filter the Select a function: list by
selecting User Defined from the Or select a category: dropdown list.
The Insert Function window (Excel 2007) The Insert Function window (Excel 2000 -03)
Excel Level 6: VBA Intermediate) Function Procedures
Help pages are not available for user-defined functions. These have to be created
using Microsoft tools that are not part of VBA or Office.
Procedures
1. Select the cell where you want to use the user-defined function.
Procedures
Excel 2000 - 2003 Excel 2007
1. Click the Tools menu. Click the View tab on the Ribbon.
2. Select Macro Macros... Click the Macros button.
3. Select View Macros....
4. Type the name of the Type the name of the user-defined
user-defined function in function in the Macro name: text box.
the Macro name: text box.
5. Click the Options button. Click the Options button
6. Type a description for the Type a description for the macro.
macro.
7. Click OK. Click OK.
8. Click Cancel. Click Cancel.
Excel Level 6: VBA Intermediate) Function Procedures
The description for the macro will appear when the macro is selected in the Insert
Function window.
The loop repeats for as many cells as there are in the given argument (cells_to_sum).
At each iteration of the loop, the value of MYSUM becomes its previous value plus
the value of the next cell in cells_to_sum.
In the example shown in the pictures below, the loop iterates through the range C3 to
C9.
The value of MYSUM first time round the loop will be 0 (the value in the first cell).
The second time round the loop the value of MYSUM will be 3000 (its old value 0,
plus 3000 the value in the second cell of cells_to_sum); the third time round the
loop the value of MYSUM becomes 6200 (its old value 3000, plus 3200 the value in
the third cell of cells_to_sum). Hence, by the time it has completed the loop, the value
of MYSUM has risen to 12300. In essence, the loop carries out a cumulative addition
of cells_to_sum.
Procedures
1. Launch or switch to the VB Editor.
Excel Level 6: VBA Intermediate) Function Procedures
EXERCISES
USER DEFINED FUNCTIONS
5. Use the function on cell F23 of the spreadsheet, using the range A2:E20 as the
argument. The result should be 57.
6. Save and close the file.
LESSON 4 - ADD-IN APPLICATIONS
In this lesson, you will learn how to:
Create an Add-In
DEFINING AN ADD-IN
Discussion
An Excel Add-in is a compiled version of a workbook containing procedures,
toolbars and menu configurations, user-defined functions and forms and many other
VBA features. Add-ins usually provide additional functionality that makes the
standard application more powerful. In its simplest form the Add-in may just contain
user-defined functions.
An Add-in is saved like other files to a suitable location on your system (it has a .xla
extension) and added in when/if necessary to the Excel installation on your
computer. Like the Personal Macro Workbook, the Add-in file is normally kept
hidden in Excel, but can be viewed in the VB Editor.
Add-ins are a convenient way of distributing sub procedures, functions and other
VBA functionality to groups of users who can load them into their own Excel
application via a simple dialog box.
Excel comes with several built-in Add-ins; the number available varies with the
version. These can be accessed and loaded by opening the Add-ins dialog box.
When a workbook is saved as an Add-in, Excel converts its code into a compressed
form that cannot be read, altered or converted back into a workbook. This is to make
the code in the Add-in work more quickly than in the original workbook.
The workbooks Title and Comments, set in File Properties, are used as the name and
description to help identify Add-ins.
Because a compiled Add-in cannot be converted back to a workbook, it is essential
that before saving as an Add-in, the workbook is saved separately as a workbook. If
changes are needed, therefore, they can be written into the original workbook and
then resaved as another (or the same) Add-in.
When a workbook is made into an add-in, worksheets in the workbook are hidden,
and subroutines in the Add-ins project are hidden from the user (the routines do not
appear in the macros dialog box).
Excel Level 6: VBA Intermediate Add-Ins
If the Add-in is saved to the XLSTART folder, its functionality applies as if it was
built into Excel.
9. Click OK.
The Save As dialog box (Excel 2003 shown). Appearance may vary
slightly between versions but basic functionality is the same.
INSTALLING AN ADD-IN
Discussion
Once the Add-in has been created, prepared and saved as described in the topics
above, you, and other users, will need to install it on your (their) computer to make
the code available for use.
This is achieved by opening the Add-ins dialog box and depending on where it has
been saved, either selecting it from the list (if it has been saved in the default location)
or browsing to the location that it has been saved in (if you have selected your own
location).
If the Add-in file has been saved in the default location, it will appear in the list with
the name that you gave it as a Title in File Properties. If the Add-in file has been saved
in a different location, it will appear in the list after your browse for it.
After the Add-in has been selected and the dialog box confirmed, the procedure(s) in
it will be immediately available for use.
Excel Level 6: VBA Intermediate Add-Ins
Procedures
Excel 2000 - 03 Excel 2007
1. Click the Tools menu. Click the Microsoft Office
Button.
2. Select Add-ins. Click the Excel Options
button.
3. Click the checkbox beside Select Add-ins in the pane at
the Add-in that you want the left.
to install, or...
EDITING AN ADD-IN
Discussion
If you encounter errors and need to debug the code in your add-in, you can make the
add-in visible and view the code provided you supply the proper project password.
Excel Level 6: VBA Intermediate Add-Ins
Once the project is unprotected, you can view, debug the code and resave the Add-in.
Procedures
1. Launch or switch to the VB Editor.
2. In the Project Explorer pane, double click the Add-in
(.xla file) in that you want to edit.
3. If password protected, you will be prompted for the
password.
4. Open the module containing the function procedure(s)
that you want to edit.
5. Make necessary changes to the code.
6. Click the Save button in the VB Editor.
REMOVING AN ADD-IN
Discussion
If you have many Add-in installed into Excel it can slow down its performance,
particularly when starting up and it has to load them all.
It is a good idea, therefore, to uninstall any Add-ins that are no longer required for
use. This does not delete the Add-in file (.xla); the file will still be available for re-
installing another time.
Procedures
Excel 2000 - 03 Excel 2007
1. Click the Tools menu. Click the Microsoft Office
Button.
2. Select Add-ins. Click the Excel Options
button.
3. Click the checkbox beside Select Add-ins in the pane at
the Add-in that you want the left.
to uninstall.
At the bottom of the pane at
the right, click the Go...
button,
Click the checkbox beside the
Add-in that you want to
uninstall.
Excel Level 6: VBA Intermediate Add-Ins
EXERCISE
WORKING WITH AN ADD-IN
1. Open the file named, Conversions. This file contains several function procedures.
2. Carry out the necessary actions to save this file as an add-in, named Conversion
Functions.
3. Close the file.
4. Open the file named, Needs Functions.
5. Add into Excel the Conversion Functions saved above.
6. Test a couple of the functions on Sheet1.
7. Save and close Needs Functions.
8. Remove the Conversion Functions add-in from Excel.
LESSON 5 TESTING AND DEBUGGING CODE
In this lesson, you will learn how to:
The good news is that the VB Editor can identify many language and compile errors
as soon as you press Enter at the end of a statement (or use the up/down arrow, or
click onto another statement). These errors, therefore, can normally be corrected
immediately. Some language and compile errors, however, can only be identified
during run-time.
In most cases, the cause of run-time errors can also be identified because the
procedure comes to a halt with a Run-time error message. If the Debug button is
clicked, it highlights in yellow the statement that failed (a condition known as break
mode).
Excel Level 6: VBA Intermediate) Testing & Debugging Code
Logical errors can be the most difficult to pin down and discovering the cause
usually involves going through the procedure statement by statement (a technique
known as stepping) until it becomes apparent where it goes wrong.
Stepping can also be used in conjunction with the Watch or the Locals window.
These keep an eye on your variable as you step the code and can indicate where and
when a variable may not be behaving as expected!
The VB Editor provides various tools to help locate the source and cause of any run-
time errors detected. This lesson will examine four of them:
1. Stepping
2. Watching variables
3. Creating Breakpoints
4. Using the Immediate Window
Step Into
Normally, your code runs unattended; it executes until its logical end. When you are
testing code, however, it is often useful to step through it line by line, watching each
line of code take effect. This makes it easy to determine exactly which line is not
producing the desired effect.
You can step through code line by line by selecting Step Into from the Debug menu of
the VB Editor or, by pressing the F8 key to start the procedure in which the cursor is
and then pressing F8 to step each statement.
Stepping causes VBA to execute each line one at a time, highlighting the next line of
code in yellow. Note, the highlighted line is the line of code that will execute when
you next press F8; it does not mean it has already been executed.
Excel Level 6: VBA Intermediate) Testing & Debugging Code
Button Function
Toggle Placing Breakpoints within your code will
Breakpoint stop execution at that point.
Quick After selecting an expression, you would use
Watch the Quick Watch button and Add button. The
watch window will show the information
about the expression. (Use Step Into).
Step Into Using the Step Into button allows you to
execute one line of code at a time
Step Over Step Over executes called sub Procedures
without stepping through them.
Step Out Step Out completes execution of the current
procedure and pauses on the next line.
Step Over
If you are stepping a procedure that calls another procedure, the VB Editor will step
into the called procedure and execute it line by line.
You can, therefore, click Debug, Step Over (or press SHIFT F8) to cause the entire
called procedure to be executed immediately. This will make debugging simpler if
you are confident that the problem does not lie within that called procedure.
Step Over takes you back to the statement following where the called procedure was
called.
Excel Level 6: VBA Intermediate) Testing & Debugging Code
Step Out
In you are stepping through a called procedure statement-by-statement, you can click
Debug, Step Out (or press CTRL+SHIFT+F8) to come out of the that procedure. This
causes VBA to execute until the end of the procedure (an End Sub or Exit Sub
statement) and then stop at the line of code immediately following the line that called
the procedure.
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) containing the procedure that you want to
step through.
3. Open the module sheet containing the procedure.
4. Click the Debug menu.
5. Select Step Into.
6. Continue selecting Step Into (or press F8) until you get to
the end of the procedure.
Excel Level 6: VBA Intermediate) Testing & Debugging Code
Locals Window
The Locals Window displays all the variables in a procedure (as well as global
variables declared at the project or module level), and their values. This makes it easy
to see exactly what the value of each variable is at a particular point in the procedure
and how it changes as you step through the code. You can display the Locals
Window by choosing it from the View menu. The Locals Window does not allow you
to change the values of variables, it simply displays their names and values.
Excel Level 6: VBA Intermediate) Testing & Debugging Code
Procedure
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) containing the procedure that you want to
add a watch to.
Excel Level 6: VBA Intermediate) Testing & Debugging Code
Watch Window
The Watch Window allows you to be more selective about which variable(s) you
"watch." You can set a variable with three watch types:
Watch Type Description
Watch Expression Watches the variable statement-by-statement as you
step through the procedure (same as Locals Window).
Break When Value Is Halts the procedure and enters break mode when the
True variable is given a value (value becomes TRUE).
Break When Value Halts the procedure and enters break mode each time
Changes that the value of the variable changes.
Procedure
1. Launch or switch to the VB Editor.
Excel Level 6: VBA Intermediate) Testing & Debugging Code
BREAK MODE
Discussion
A break point is a setting on a line of code that tells VBA to pause execution
immediately before that line of code is executed and code execution is placed in what
is called break mode. When the VB Editor is in break mode, you can edit the procedure
as normal.
To put a break point on a line of code, place the cursor on that line select Debug,
Toggle Breakpoint, press F9, or click in the grey bar at the left of the module next to
the line where you want to add the break point.
Removing a break point is the same as applying one (hence, toggle).
When a line contains a break point, it is displayed with a brown coloured
background and a large dot in the grey band at the left of the module sheet.
Immediately before this line of code is executed, it will appear with a yellow
background. When a break point is encountered, code execution is paused but that
line of code has not yet executed. You cannot place break points on blank lines,
comment lines, or variable declaration lines (lines with Dim statements).
Excel Level 6: VBA Intermediate) Testing & Debugging Code
After a break point is encountered, you can resume normal code execution by
pressing F5, selecting Run, Continue, clicking the Continue button, or stepping
through the code line by line (F8).
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code that you
want to add a breakpoint to.
4. Position the cursor in the procedure where you want to
add the breakpoint.
5. Click the Debug menu.
6. Select Toggle Breakpoint.
Immediate Window
The Immediate Window is a window in the VB Editor where you can try out
statements and/or variables while your code is in Break mode or when no macro
code is executing. It is most useful when testing new or problematic code.
To display the Immediate Window, press CTRL+G or select View, Immediate
Window.
In the Immediate Window, you can test a statement by typing it in and pressing
Enter. For example:
Range(A1).CurrentRegion.Select
or,
Selection.Interior.Color = vbMagenta
numCols = Selection.Columns.Count
?numCols
12
Or,
?ActiveCell.Address
$A$10
Because of the way that the Immediate Window is designed to work, it will not allow
you to test statement blocks (eg, If..., For... , Select Case... etc.). You can, however,
combine several "logical" lines of code in to a single "physical" line of code using
the colon (:) and execute this as an entire command. For example:
Procedures
1. Launch or switch to the VB Editor.
2. Click the View menu,
Excel Level 6: VBA Intermediate) Testing & Debugging Code
Debug.Print
You can use the Debug.Print statement anywhere in your code to display messages
or variable values in the Immediate Window. These statements do not require any
confirmation or acknowledgement so will not affect the execution of your code, so it
is safe to leave in the code when it is distributed to your users.
They are used purely to explain, clarify, remind or note what is taking place at a
particular point of the procedure.
They are much like comments except that they are written for you to see in the
Immediate Window. If the Immediate Window is not displayed, Debug.Print has no
effect.
For example, you can send a message to the Immediate Window when a particular
section of code is executed.
Some code...
Debug.Print "Starting Code Section 1"
More code...
Debug.Print Procedure is now calling Procedure2
EXERCISE
TESTING AND DEBUGGING CODE
Or,
If ActiveCell.Address = $A$1 Then
...code
Else
MsgBox Incorrect cell selected. Select A1 and run again
Exit Sub
End If
In both cases, the selection is tested and if true, a message is displayed to explain the
problem before terminating execution of the procedure.
In the following example, an input box is displayed for the user to enter a number. If
the user accidentally enters a text value or clicks Cancel (both string values), a run-
time error occurs when the procedure attempts to use the string in the calculation.
Excel Level 6: VBA Intermediate) Error Handling & Trapping
By using an If... Then... Else function, together with the IsNumeric function to check
that the input is valid before attempting the calculation, the run time error can be
handled in a more user-friendly way, eg:
There are several Is... functions in VBA that can be used in a similar way:
IsArray
IsDate
IsEmpty
IsError
IsMissing
IsNull
IsObject
Procedures
1. Launch or switch to the VB Editor.
Excel Level 6: VBA Intermediate) Error Handling & Trapping
ERROR TRAPPING
Discussion
While If...Then...Else is a good, simple way of testing for correct input, it is not able
to handle all errors under all circumstances. In most cases, error trapping code will
almost certainly be needed. This come in three forms:
On Error Resume Next
On Error GoTo
Resume
The error trap is turned on and sits in wait until an error occurs or until the
trap is turned off. The On Error statement is normally written into the procedure
just above where the anticipated error may occur. In many cases, this will be at the
top of the procedure just below any variable and/or constant declarations.
On Error Resume Next tells the procedure to ignore any statements producing a run-
time error, and continue with the next statement.
The code below is designed to hide all toolbars. Some toolbars, however, do not have
a visible property and the following run-time error will be generated.
By writing the code as follows, the run-time error window will be ignored and the
procedure will successfully continue and hide all the toolbars.
The following example deletes ALL files from three folders (Data1, Data2 and Data3)
on the H:\ drive.
Kill "h:\Data1\*.*"
Kill "h:\Data2\*.*"
Kill "h:\Data3\*.*"
If a folder does not contain any files, the following run-time error message will occur:
Excel Level 6: VBA Intermediate) Error Handling & Trapping
This is a classic case of where the error can be ignored; if the folder is already empty,
then it does not need emptying, so VBA can safely ignore it and continue with the
next one!
Kill "h:\Data1\*.*"
Kill "h:\Data2\*.*"
Kill "h:\Data3\*.*"
In the earlier example on page 84 where the user is prompted for a numeric input, On
Error Resume Next would negate the need for the If... Then... Else.
errhandle:
MsgBox "Invalid Data entered or user clicked Cancel"
End Sub
It is true that this code in its current form does not contribute any more than using
the If...Then...Else explained on page 84. Its advantage, however, lies in its ability to
return to where the error occurred and attempt the statement again. This involves the
use of the word Resume.
Resume
The keyword Resume tells VBA to retry the statement that failed. It can only be used
as part of an error handling routine, and is always used on its own (eg. On Error
Resume will cause an error). The error handling routine above, therefore, could
explain the problem the return the user to try again as follows:
errhandle:
MsgBox "Invalid Data entered or user clicked Cancel"
Resume
End Sub
The code above, however, does not give the user an opportunity NOT to return and
try again. So the next step in making the error handling routine as user-friendly as
possible, is to provide an interactive message box displaying a message explaining
the problem, asking whether the user WANTS to try again, and providing two
buttons (Yes and No) with which to respond.
Excel Level 6: VBA Intermediate) Error Handling & Trapping
errhandle:
response = MsgBox("Invalid Data Entered. Do you want to try again?", vbYesNo)
If response = vbYes Then
Resume
End If
The final (and very important!) step is to prevent the error handling routine being
executed when the procedure runs WITHOUT any errors. This is achieved by
including the words Exit Sub immediately above the error routine label. The
complete procedure with error handling code is given below:
Sub CalculateInterest
Exit Sub
errhandle:
response = MsgBox("Invalid Data Entered. Do you want to try again?", vbYesNo)
If response = vbYes Then
Resume
End If
End Sub
Excel Level 6: VBA Intermediate) Error Handling & Trapping
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor on the line below the Sub statement.
5. Type On Error GoTo errhandle (or other label to
identify a point further down in the procedure where the
procedure must divert to if a runtime error occurs.
6. A the bottom of the procedure and immediately above
the End Sub statement, type errhandle (or other label
used).
7. Type a colon.
8. Press Enter.
9. Type appropriate error handling code for the anticipated
error using the examples above.
10. Position the cursor on the line immediately above the
errhandle label.
11. Type Exit Sub.
12. Press Enter.
Sub CalculateInterest
Sheets("Interest Calcs").Activate
Exit Sub
errhandle:
Resume
End If
End Sub
The solution is to substitute the following code as the error handling routine:
errhandle:
If Err.Number = 13 Then
response = MsgBox("Invalid Data Entered. Do you want to try again?", vbYesNo)
If response = vbYes Then
Resume
End If
ElseIf Err.Number = 9 Then
MsgBox ("Sheet Interest Calc not found. Please check sheet names and re-run procedure")
Else
MsgBox "Unexpected error. Procedure will terminate"
End If
Excel Level 6: VBA Intermediate) Error Handling & Trapping
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor on the line below the Sub statement.
5. Type On Error GoTo errhandle (or other label to
identify a point further down in the procedure where the
procedure must divert to if a runtime error occurs.
6. A the bottom of the procedure and immediately above
the End Sub statement, type errhandle (or other label
used).
7. Type a colon.
8. Press Enter.
9. Type If.
10. Type a space.
11. Type err.Number = .
12. Type the anticipated error number.
13. Type a space.
14. Type Then.
15. Press Enter.
16. Type appropriate code to handle the error generated by
the error number in the previous test.
17. Press Enter.
18. If it is anticipated that the procedure may generate
additional error numbers, type ElseIf.
19. Type a space.
20. Type err.Number = .
21. Type the anticipated error number.
22. Type a space.
23. Type Then.
24. Press Enter.
25. Type appropriate code to handle the error generated by
the error number in the previous test.
Excel Level 6: VBA Intermediate) Error Handling & Trapping
On Error GoTo 0
This statement disables a previous On Error Resume Next or On Error Goto Label
statement. When the next error occurs, an error message will be generated and the
procedure will fail, eg:
Kill "h:\Data1\*.*"
Kill "h:\Data2\*.*"
Kill "h:\Data3\*.*"
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
Excel Level 6: VBA Intermediate) Error Handling & Trapping
Err.Description
A common way of creating a user-friendly run time error message is by creating a
custom message box quoting the error number and the error description. For
example, the code could be as follows (line continuation characters have been used
for clarity but are not required):
It is true to say that this message box does not say much more than the normal, run-
time error window, but it is rather less scary and upon clicking OK, does not
potentially leave the procedure hanging in break mode.
Excel Level 6: VBA Intermediate) Error Handling & Trapping
EXERCISE
DEALING WITH POTENTIAL ERRORS IN PROCEDURES
Application.Dialogs(xlDialogSaveAs).Show
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook
(VBA project) that you want to add code to.
3. Open the module sheet containing the code or, insert a
new module.
4. Position the cursor in the procedure where you want to
show the built-in dialog box.
5. Type Application.
6. Type a full stop.
7. Type Dialogs.
8. Type an opening bracket (.
9. Type or select from the list the dialog box required.
10. Type a closing bracket ).
11. Press Enter.
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
USER-DEFINED FORMS
Discussion
As with built-in dialog boxes, User-Defined Forms (or just User Forms) can be
created to allow an applications to interact with the user. UserForms are, in essence,
dialog boxes that you design yourself for a special purpose that is not met by the
built-in ones.
Creating a functioning UserForm can be broken down into five steps:
1. Inserting a blank UserForm into a workbook
2. Adding controls to the form.
3. Giving the controls necessary properties.
4. Adding VBA code behind the form in order to make it respond to the user
input.
5. Adding code to display the form.
Procedures
1. Launch the VB Editor.
2. Right-click the workbook that you want to insert the
UserForm into.
3. Point to Insert .
4. Select UserForm.
inserted into a workbook in the VB Editor, and are quite literally drawn onto the
form.
It is advisable to have clear in your mind what controls the form should contain
before you start. Design the form on paper before you start.
Procedures
1. Click in the Toolbox, the button for the control that you
want to draw on the form.
2. Click the mouse pointer (black cross) on the form where
you want the top left corner of the control to be placed.
3. Point to the grey border on the edge of the control
arrow.
6. Click and drag to resize the control, if necessary.
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
it.
8. Continue drawing, moving and resizing controls as
necessary.
Procedures
1. Click the first control that you want to include in the
group.
2. Hold down the SHIFT key.
3. Click the next control that you want to include in the
group.
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
CONTROL PROPERTIES
Each form control has a list of properties that can be displayed and (if necessary)
changed in the Properties pane.
Many properties can be modified by directly formatting the control on the form;
others are set from the properties window. Properties can also be set or modified at
run-time, ie. when the form is displayed.
A comprehensive list of all properties for all form control would be too long and
unnecessary for this booklet, but help can be sought by clicking onto a property in
the properties pane and pressing F1.
For the purposes of a UserForm, the property that would usually need to be set for all
controls on the form is the Name property. Giving the controls a clear, consistent and
descriptive name makes them easier to identify when it comes to programming the
form.
PROGRAMMING A USERFORM
Discussion
UserForms and controls have a predefined set of events. For example a command
button has a click event, a procedure that runs when the user clicks the command
button. UserForms have an initialise event that runs when the form is loaded.
In order for a UserForm to work in the expected way (ie. as a dialog box), it has to
have at least two event procedure one for when the OK button is pressed and a
second for when the Cancel button is pressed.
To write a control or form event procedure, open a module by double clicking the
form or control. A default event will appear on the module sheet but this can be
changed by selecting a different one from the procedure drop-down list at the top
right of the window.
Event procedures include the name of the control. For example, the name of the click
event procedure for a command button named cmdOK is
Private Sub cmdOK_Click. Private because the sub procedure should not show in
the Macro list in Excel, it does not need to because it is purely for use by the OK
button on the form.
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
Procedures
1. Double click the Cancel button on the form design.
2. Add code as necessary (see examples below).
3. Double-click the form in the Project Explorer pane.
4. Double-click the OK button on the form design.
5. Add code as necessary (see examples below).
6. Double click the form in the Project Explorer pane.
All the possible ways of programming a form and its controls events are too
numerous and varied to mention in any document. The examples given below,
therefore, apply to the more commonly used controls and are given as a guide only.
Additional examples and help can be obtained from the VB Editor help, and on
various websites including the Microsoft Developer Network at:
http://msdn.microsoft.com/en-us/library/aa220733(office.11).aspx
Unload frmDataEntry
d) Check boxes, toggle buttons, and options button on the form will need to be
tested to ascertain which condition(s) apply.
e) The form itself must be removed from the screen after all the above tasks have
been completed.
The following examples all apply to the click event of the OK button and can be
written in any order. When referring to the control, its name as defined in the
properties pane must always be preceded by the name of the form that it is on, eg:
frmDataEntry.txtName.Value
frmDataEntry.txtName.Value
you can use...
Me.frmDataEntry.txtName.Value
Text Boxes
Typically, when the OK button is clicked, text entered into a text box will need to be
transferred to a cell on a sheet, eg:
ActiveSheet.Range(A2).Value = frmDataEntry.txtName.Value
Value can be omitted because VBA always defaults to the value property for a
range object if the method or property is omitted. In addition, if the form must write
the text into cell A1 of the sheet that the form is being run from, there is no need to
include ActiveSheet. Hence, the code can be abbreviated to:
Range(A2) = Me.txtName
Range(A3) = Me.cmbDepartment
or
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
Range(A4) = Me.lstLocation
Under other circumstances, it may be that the combo box or list box is designed to
give the user options to choose from. In the following example, a list box has been
used to give the user a choice of files to open. The code, therefore, would be:
The above code assumes that the file to open is in the active, default folder. It may be
safer, therefore, to concatenate the correct path to the value returned by the control,
eg:
In the following example, a combo box has been placed on the form to give the user a
selection of fonts to use. Assuming that the range to format is A1 to E1, the code
would be as follows:
Range(A1:E1).Font.Name = Me.cmbFontName
Option Buttons
Although not necessary if only one set of option buttons are used on a form, it is
good practice to draw them inside a frame. Only one option button can be selected at
a time so when one button is pressed in, another is pushed out (hence, radio
buttons).
Invariably, a decision will need to be made which option button is selected and thus,
an If structure used to carry out the necessary actions.
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
In the following example, a frame has been set up on a form with two option buttons,
one for selecting male and one for selecting female. Whichever of the two is chosen
must be placed into cell B4 as M or F.
Range(B4).Value = M
Else
Range(B4).Value = F
End If
Check Boxes
Because a check box has two conditions true or false, an If statement has to be used
to evaluate them. In the following example, a check box has been used for the user to
state whether to print the workbook or not.
ActiveDocument.PrintOut
End If
The code for making the value of the spin button visible in the text box would be
added to the spin buttons On_Change event. As the value in the spin button
changes, it is transferred to and made visible in the text box.
Procedures
1. Double-click the spin button on the form design.
2. Add the following code to the buttons On_Change event
procedure.
a. Private Sub spnCopies_Change()
i. Me.<text box name> = Me.<spin box name>
b. End Sub
3. Double-click the form in the Project Explorer pane.
The above procedure is purely to make the value of the spin button visible to the user
while using the form. Additional code has to be added to the OK buttons on click
event to make use of the spin buttons value.
In the following example, a spin button has been created on a form to prompt the
user for how many copies to print. The code uses the spin buttons value to print the
requested number of copies.
ActiveSheet.PrintOut Copies:=Me.spnCopies
FORM EVENTS
The topic above deals with events associated with form controls. The form itself also
has events that can be assigned a procedure. As with control events, the number
and variety of examples is too great to cover in this booklet. A couple of commonly
used examples, however, are given below to demonstrate use of the Initialize event.
The initialize event occurs when the form loads (just before it becomes visible on the
screen) and is often used to set default values for its controls and for populating
combo and list boxes.
Example A populates a combo box with four cities and Example B applies default
values to a text box and check box.
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
Example A
With Me.cmbLocations
.AddItem Belfast
.AddItem Cardiff
.AddItem Edinburgh
.AddItem London
End With
End Sub
Example B
Me.txtLocation.Value = London
Me.chkPrint.Value = True
End Sub
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
DISPLAYING A USERFORM
To display a user form, use the Show method for the form in question. This would be
written on a normal module sheet in the same workbook that the form has been
created in. The following example displays the UserForm named frmDataEntry:
Sub DisplayForm()
frmDataEntry.Show
End Sub
Once the procedure has been written, a method of running it from Excel needs to be
chosen. This would be the same as for any other macro, ie. button, menu or
keystroke. The code could also be included as part of a larger procedure, or called
into one as a separate sub procedure.
Procedures
1. Launch the VB Editor.
2. Identify the workbook containing the form that you want
to show.
3. Insert a module sheet in the workbook.
4. Type the following code:
Sub ShowForm
<formname>.Show
End Sub
5. Run the userform
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
EXERCISE
CREATING A USERFORM
Task 1 - To create a UserForm to prompt for Text, ComboBox and CheckBox information.
Label
Text Box
Command
Buttons
Label
Combo Box
Check
Boxes Image
5. Double-click the form in the Project Explorer to return to its design window.
6. Assign an initialize event to the form (what happens when the form starts up) by
double clicking the form background and typing the following code. This is
necessary to load (populate) the combo box:
With frmDataEntry.comColours
.AddItem "Red"
.AddItem "Blue"
.AddItem "Green"
End With
7. Return to the form design window.
8. Double-click the OK button and add the following code. This is necessary to
implement the userform:
Range("A1").Value = frmDataEntry.txtInput.Value
Select Case frmDataEntry.comColours
Case Is = "Red"
Range("A1").Font.Color = vbRed
Case Is = "Blue"
Range("A1").Font.Color = vbBlue
Case Is = "Green"
Range("A1").Font.Color = vbGreen
End Select
If frmDataEntry.chkBold = True Then
Range("A1").Font.Bold = True
Else
Range("A1").Font.Bold = False
End If
If frmDataEntry.chkItalic = True Then
Excel Level 6: VBA Intermediate) Dialog Boxes and Userforms
Range("A1").Font.Italic = True
Else
Range("A1").Font.Italic = False
End If
Unload frmDataEntry
9. Finally, write a short sub procedure on a new module sheet to show the form:
Sub EnterData()
frmDataEntry.Show
End Sub
10. Create a custom button on your toolbar to run the EnterData macro and check
correct data entry in cell A1. Correct any code, if necessary.
11. Save and close the file.
Excel Level 6: VBA Intermediate) Appendix I Sub Procedure Add-ins
Discussion
In order for a workbook containing sub procedure(s) to be used as an Add-in, there
must be a way for the Add-in to add a menu or buttons to run the procedure(s) when
it is installed.
In order to achieve this, the following two (or similar) procedures needs to be added
to the ThisWorkbook Excel Object module sheet as Private Subs (one that is not seen
from the Excel side because it is not relevant to run it from there).
The Add-in can then be protected, saved and installed as described in lesson 6 on
page 59.
Option Explicit
' This procedure adds a menu command to run the procedure when the Add-in is installed
'Delete any existing menu item that may have been left
With cControl
.Style = msoButtonCaption
.OnAction = "MyGreatMacro"
End With
On Error GoTo 0
End Sub
Excel Level 6: VBA Intermediate) Appendix I Sub Procedure Add-ins
' This procedure removes the menu command when the Add-in is un-installed
On Error GoTo 0
End Sub
Excel Level 6: VBA Intermediate) Appendix II Error Codes
Code Message
3 Return without GoSub
5 Invalid procedure call
6 Overflow
7 Out of memory
9 Subscript out of range
10 This array is fixed or temporarily locked
11 Division by zero
13 Type mismatch
14 Out of string space
16 Expression too complex
17 Can't perform requested operation
18 User interrupt occurred
20 Resume without error
28 Out of stack space
35 Sub, Function, or Property not defined
47 Too many code resource or DLL application clients
48 Error in loading code resource or DLL
49 Bad code resource or DLL calling convention
51 Internal error
52 Bad file name or number
53 File not found
54 Bad file mode
55 File already open
57 Device I/O error
58 File already exists
59 Bad record length
Excel Level 6: VBA Intermediate) Appendix II Error Codes
61 Disk full
62 Input past end of file
63 Bad record number
67 Too many files
68 Device unavailable
70 Permission denied
71 Disk not ready
74 Can't rename with different drive
75 Path/File access error
76 Path not found
91 Object variable or With block variable not set
92 For loop not initialized
93 Invalid pattern string
94 Invalid use of Null
97 Can't call Friend procedure on an object that is not an instance of
the defining class
98 A property or method call cannot include a reference to a private
object, either as an argument or as a return value
298 System resource or DLL could not be loaded
320 Can't use character device names in specified file names
321 Invalid file format
322 Can't create necessary temporary file
325 Invalid format in resource file
327 Data value named not found
328 Illegal parameter; can't write arrays
335 Could not access system registry
336 Component not correctly registered
337 Component not found
338 Component did not run correctly
360 Object already loaded
361 Can't load or unload this object
363 Control specified not found
364 Object was unloaded
365 Unable to unload within this context
Excel Level 6: VBA Intermediate) Appendix II Error Codes
368 The specified file is out of date. This program requires a later
version
371 The specified object can't be used as an owner form for Show
380 Invalid property value
381 Invalid property-array index
382 Property Set can't be executed at run time
383 Property Set can't be used with a read-only property
385 Need property-array index
387 Property Set not permitted
393 Property Get can't be executed at run time
394 Property Get can't be executed on write-only property
400 Form already displayed; can't show modally
402 Code must close topmost modal form first
419 Permission to use object denied
422 Property not found
423 Property or method not found
424 Object required
425 Invalid object use
429 Component can't create object or return reference to this object
430 Class doesn't support Automation
432 File name or class name not found during Automation operation
438 Object doesn't support this property or method
440 Automation error
442 Connection to type library or object library for remote process
has been lost
443 Automation object doesn't have a default value
445 Object doesn't support this action
446 Object doesn't support named arguments
447 Object doesn't support current locale setting
448 Named argument not found
449 Argument not optional or invalid property assignment
450 Wrong number of arguments or invalid property assignment
451 Object not a collection
452 Invalid ordinal
Excel Level 6: VBA Intermediate) Appendix II Error Codes
Discussion
In Excel 2000 and later, you can use Debug.Assert statements to cause the code to
break if a condition is not met. The syntax for Debug.Assert is:
Debug.Assert (condition)
Dim X As Long
X = 123
Debug.Assert (X < 100)
Conditional Compilation
While not directly part of debugging code, conditional compilation allows you to
create "debug" and "release" versions of your code. For example, you may want to
include message boxes, or Debug.Print or Debug.Assert statements while you are
developing and testing your code, but you do not want those to be active when you
release the code to users. VBA allows you to include or exclude blocks of code with a
technique called conditional compilation. Conditional compilation uses If, Then, and
Else statements to include or exclude a block of code. First, you want to create a
compiler variable called, for example, DEBUG_ . Use the #CONST directive to create
the variable.
#CONST DEBUG_ = True
Then, delimit blocks using the compiler directives to include various blocks of code.
For example,
Excel Level 6: VBA Intermediate) Appendix III Debug.Assert
#If DEBUG_ Then
Debug.Assert (X<100)
#End If
Note the use of the # character. In your development version, keep the value of
DEBUG_ equal to True. When you are ready to release the code to end users, set this
one constant value to False to prevent the Debug.Assert statement from even being
included in the compiled code.
Excel Level 6: VBA Intermediate) Appendix IV Adding Interactivity
Discussion
Examples of where an interactive message box might be required are where
confirmation is required to proceed with the next part of a procedure, or in error
handling, eg.
Example A Example B
To make the message box interactive, the arguments must be put inside brackets. The
following code will display Example A above.
MsgBox ("Do you want to continue deleting the data", vbYesNo, "Delete Confirm")
Prompt Buttons Title
The buttons argument consists of constants or values from each of the following
three groups:
Icon style:
Constant Value Display Icon
Excel Level 6: VBA Intermediate) Appendix IV Adding Interactivity
Default Button:
Constant Value Default
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 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.
vbQuestion
vbYesNo vbDefaultButton2
(second from left)
A more concise method of writing the above sample of code would be to use the
numeric values for the arguments, eg.
4 + 32 + 256
Procedures
1. Position the cursor in the sub procedure code where you
want to place the statement.
Excel Level 6: VBA Intermediate) Appendix IV Adding Interactivity
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:
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.))
Excel Level 6: VBA Intermediate) Appendix IV Adding Interactivity
Sub CreateTable()
Sheets.Add
End Sub
Sub TestProfit()
cel.Font.Bold = True
Else
cel.Font.Color = vbRed
End If
Next cel
End Sub
Excel Level 6: VBA Intermediate) Appendix V - Solutions to Exercises
Sub LayoutTable()
ActiveCell.CurrentRegion.Select
Selection.ColumnWidth = 12
Selection.Columns(1).Font.Color = vbBlue
Selection.Rows(1).HorizontalAlignment = xlCenter
End Sub
Sub FormatNumbers()
ActiveCell.CurrentRegion.Select
Selection.Offset(1, 1).Select
Selection.Resize(Selection.Rows.Count - 1, Selection.Columns.Count - 1).Select
Selection.NumberFormat = "#,##0.00"
End Sub
Sub LastCell()
Selection.CurrentRegion.Select
Selection.Cells(Selection.Cells.Count).Select
ActiveCell.Font.Size = 14
ActiveCell.Interior.Color = vbYellow
ActiveCell.EntireColumn.AutoFit
End Sub
Sub RunAllMacros()
Call LayoutTable
Call FormatNumbers
Call LastCell
End Sub
Excel Level 6: VBA Intermediate) Appendix V - Solutions to Exercises
Sub CreateNewForecast()
Sheets("Template").Copy After:=Sheets(Sheets.Count)
For i = 1 To 4
Next i
For i = 1 To 4
Next i
End Sub
Task 2
Sub ApplyColours()
ActiveCell.CurrentRegion.Columns(1).Interior.ColorIndex = ORANGE
ActiveCell.CurrentRegion.Columns(1).Font.ColorIndex = BLUE
End Sub
Excel Level 6: VBA Intermediate) Appendix V - Solutions to Exercises
Task 3
Sub TransferData()
Dim arrData(1 To 6, 1 To 4)
Dim iRows As Byte
Dim iCols As Byte
For iRows = 1 To 6
For iCols = 1 To 4
Next iCols
Next iRows
Sheets("Net").Activate
For iRows = 1 To 6
For iCols = 1 To 4
Next iCols
Next iRows
End Sub
Excel Level 6: VBA Intermediate) Appendix V - Solutions to Exercises
Function DegF(TempC)
DegF = TempC * 9 / 5 + 32
End Function
Function DegC(TempF)
End Function
Function Hypot(x, y)
Hypot = Sqr(x ^ 2 + y ^ 2)
End Function
End Function
Task 2
Function CountText(RangeToCount)
CountText = CountText + 1
End If
Next numb
End Function
Excel Level 6: VBA Intermediate) Appendix V - Solutions to Exercises
Sub CircData()
Const PI = 3.142
If IsNumeric(Radius) Then
CircArea = PI * (Radius ^ 2)
CircCircumf = 2 * PI * Radius
MsgBox "The area of the circle is: " & CircArea & vbCrLf & vbCrLf & _
"The circumference of the circle is: " & CircCircumf
Else
End If
End Sub
Sub DeleteOldFile()
fileToRemove = InputBox("Type name of file to delete from the current folder", "Delete File")
Exit Sub
Else
End If
Exit Sub
errhandle:
If Err.Number = 53 Then
Excel Level 6: VBA Intermediate) Appendix V - Solutions to Exercises
fileToRemove = InputBox("Type name of file to delete from the current folder", "Delete File")
Resume
End If
End If
If Err.Number = 70 Then
MsgBox "File is currently open. Close the file and run the macro again"
End If
End Sub
Excel Level 6: VBA Intermediate) Index
INDEX
error codes - list .............................................. 119
A
error descriptions..............................................94
Add-ins Is... functions .....................................................84
code for subprocedures .................................. 117 On Error statement ...........................................85
creating ............................................................. 61 Resume statement.............................................85
editing............................................................... 64 trapping with error numbers ...........................90
installing to Excel ............................................. 63 using interactive message boxes ......................88
overview ........................................................... 60 using labels to divert code ...............................87
removing .......................................................... 65 using the IF statement ......................................83
Arrays
F
Array function.................................................. 38
assigning values ............................................... 31 Functions
declaring ........................................................... 24 declaring variables in .......................................54
dynamic ............................................................ 35 getting help .......................................................52
lower bound ..................................................... 26 user-defined ......................................................49
multi-dimensional ........................................... 28 using Excel functions in procedures ................44
Option Base 1 ................................................... 27 using ranges in arguments ...............................55
overview ........................................................... 24 VBA functions ...................................................46
ReDim ............................................................... 36
M
ReDim Preserve ............................................... 37
using loops with............................................... 33 Message Box
adding interactivity ........................................ 125
C
button types .................................................... 125
Collections default buttons ................................................ 126
Cells .................................................................. 10 icons ................................................................. 125
ChartObjects..................................................... 11 interactive use examples ................................ 128
Columns ........................................................... 11 responding to .................................................. 128
Rows ................................................................. 11
O
Sheets ................................................................ 10
WorkBooks ....................................................... 10 Offset ......................................................................14
WorkSheets ...................................................... 10
R
Constants
declaring ........................................................... 22 Ranges
using ................................................................. 22 Cells property .................................................... 8
CurrentRegion property...................................12
D
Offset property..................................................14
Debugging referring to ......................................................... 7
Break mode ...................................................... 76 Resize property .................................................15
Debug.Assert................................................... 123 Resize .....................................................................15
Debug.Print ...................................................... 80
U
displaying variable values .............................. 73
error types ........................................................ 69 Userforms, custom
Locals window ................................................. 73 adding controls .................................................99
step into ............................................................ 70 adding events to controls ............................... 106
step out ............................................................. 72 Cancel button .................................................. 107
step over ........................................................... 71 check boxes ..................................................... 110
stepping a procedure ....................................... 70 combo boxes.................................................... 108
Watch window ................................................. 75 control properties ........................................... 104
Dialog Boxes control types.................................................... 100
using Excel dialog boxes in procedures ......... 98 creating ..............................................................99
displaying........................................................ 113
E
editing controls ............................................... 101
Error Handling form events - initialize .................................... 111
Err.Number ...................................................... 91 grouping controls ........................................... 102
Excel Level 6: VBA Intermediate) Index