VBA Error Handling
VBA Error Handling
Most of the macros you write in VBA are Sub procedures. Depends on the VBA code that you’ve
written, if you execute the Sub procedure and something happens.
As for Event procedures , all you need to do with these procedures is to add the code to be executed
when the event is triggered. (Like the Worksheet_Activate event)
And to define Function as a procedure, just think of the many Excel function that we use everyday like
MAX, SUM, AVERAGE. I believe you’re already familiar with the concept of a function. These function
takes one or more arguments and returns a single value. The same goes for Function procedures that
you can develop with VBA.
Procedures in Excel VBA can have either private or public scope. The Private and Public keywords used
with procedure definitions have a similar function to that used with variable declarations(discussed in
Part C). The use of the Private and Public keywords are optional, but VBA includes them in predefined
event procedures.
a) Sub procedures
To create a procedure, activate the VBE window and insert a module. Double click on
Module1. This will bring up the code window. Add the code shown in Figure 5.1
Figure 5.1
You start a Sub procedure with the keyword Sub and ends with an End Sub statement. Figure 5.1 show
this: The code is in the Code Window
Sub Hello()
MsgBox “Hello World!”
End Sub
This example shows a procedure named Hello. A set of parentheses follows the procedure’s name.
Most of the time, these parentheses are empty. However, you may pass arguments to Sub procedures
from other procedures. If your Sub uses arguments, list them between the parentheses.
Like the macro you recorded in Part B using the Excel macro recorder, the result is always a Sub
procedure.
As you see later in this Part, Excel provides quite a few ways to execute a VBA Sub procedure.
b) Event procedures
When something happens in Excel, its call an Event. Let’s look at a few examples…
A workbook is opened or closed.
A workbook is activated.
A worksheet is activated or deactivated.
A workbook is saved.
A worksheet is calculated.
When a button is clicked
When a particular key or key combination is pressed.
A particular time of day occurs.
An error occurs.
When you create an event procedure, VBA will automatically define it for you. Activate the VBE
window and double click on Sheet1 to bring up the Code Window. Select Worksheet and then the
Calculate event. When you do this, like the example shown in Figure 5.2, the Private Sub
Worksheet_Calculate() statement and the End Sub is set by VBA. Add the code
Private Sub Worksheet_Calculate()
MsgBox "Welcome!"
End Sub
Figure 5.2
This code when executed will display the message box “Welcome”. It will executed whenever there is
calculation in Sheet1 i.e. the Calculate event is triggered.
c) Function procedures
For a Function procedure, you start with the keyword Function and ends with an
End Function statement. Here’s a simple example:
Function SquareRoot(num)
SquareRoot = num ^ (1 / 2)
End Function
This function, named SquareRoot, takes one argument (i.e num), which is enclosed in parentheses.
Functions can have any number of arguments or none at all. When the function is executed, it returns
a single value — the square root of the argument passed to the function.
VBA allows you to define what type of value (such as data type) is returned by a Function procedure.
Part D contains more information on specifying data types.
Function can be used in only two ways. You can execute it from another procedure (a Sub or another
Function procedure) or use it in a worksheet formula.
Let’s do another example. This function is to calculate the area of a Rectangle. The formula equal :
Rectangle = Length x Width. Here’s how
Public Function Rect(ByVal length As Double, width As Double) As Double
Rect = length * width
End Function
The code is really very simple. First it ask for the user input with two input boxes i.e. the length and the
width. After that the two values is assigned to the function Rect(). Here the calculation is made and the
result is returned to the calling procedure. A msgbox will displays the area of the rectangle.
Its common sense that a procedure’s name should describe the routine’s purpose. For example,
GetUserName, InputTaxData, PerformSort_and etc.
Some programmers prefer using sentence like names that provide a complete description of the
procedure. Some examples include WriteReportToTextFile and Get_Print_Options_and_Print_Report.
The use of such lengthy names has pros and cons. On the one hand, such names are descriptive,
unambiguous and not too long. You can have your own naming style, just make the names descriptive
and to avoid meaningless names such as GetIt, DoThis, RunAgain, and Macro1.
You cannot change the name of the event procedures as they are already predefines by Excel VBA.
Here, all you need to do is search the specific event and insert code to be executed.
When the specified event happened or triggered like Worksheet_Activate, the code that you add on
this procedure will be executed. (I will discuss more on this in Part H)
Let’s start with the Sub Procedures. To execute a Sub Procedure (not an exhaustive list)
Use the Run-Run Sub/UserForm command on the VBE window. This menu command has two
alternatives: The F5 key, and the Run Sub/UserForm button on the Standard toolbar in the
VBE. (show screenshot)
In the Excel’s Macro dialog box, choose Tools-Macro-Macros or press the Alt-F8 shortcut key.
When the Macro dialog box appears, select the Sub procedure you want and click Run.
An easy one will be by pressing Ctrl+key shortcut assigned to the Sub procedure. You must
remember the shortcut key that you have assigned.
Clicking a button or a shape on a worksheet that you have assigned a Sub procedure to it.
From another Sub procedure that you write.
Automatically, when you open or close a workbook.
And, when an event occurs like worksheet activate, userform initialize etc
I will show you some of these techniques in the following sections. We will execute the procedures
done above.
The quickest way to execute this procedure is by doing so directly from the VBA module in which you
defined it. Follow these steps:
i) Activate the VBE and select the VBA module that contains the procedure.
ii) Move the cursor anywhere in the procedure’s code.
iii) Press F5 (or choose Run-Run Sub/UserForm).
iv) Click on the Run-Run Sub/UserForm
Figure 5.3
Another way to execute a macro is to press its shortcut key. But before you can use this method,
you have to set things up. Specifically, you must assign a shortcut key to the macro.
You have the opportunity to assign a shortcut key in the Record Macro dialog box when you begin
recording a macro. If you create the procedure without using the macro recorder, you can assign a
shortcut key (or change an existing shortcut key) by using the following procedure:
i) Choose Tools-Macro-Macros.
ii) Select the Sub procedure name from the list box.
In this example, the procedure is named Hello.
iii) Click the Options button.
Excel displays the dialog box shown in Figure 5.5.
iv) Click the Shortcut Key option and enter a letter in the box labeled Ctrl.
The letter you enter corresponds to the key combination you want to
use for executing the macro. Here you enter the letter c, you
can then execute the macro by pressing Ctrl+h.
v) Click OK or Cancel to close the Macro Options dialog box.
Figure 5.5
After assigning a shortcut key, you can press that key combination to execute the macro. Please note
that the shortcut keys you assign to macros override Excel’s built-in shortcut keys. For example, if you
assign Ctrl+C to a macro, you can’t use this shortcut key to copy data in your workbook like you usually
do.
Another way for executing the macro is by assigning the macro to a button (or any other shape) on a
worksheet. To assign the macro to a button, follow these steps:
i) Activate a worksheet.
ii) Add a button from the Forms group.
iii) Click the Button tool in the Forms group.
iv) Drag in the worksheet to create the button.
After you add the button to your worksheet, Excel will displays the Assign Macro dialog box
automatically.
v) Select the macro you want to assign to the button.
vi) Click OK.
Clicking the button will execute the macro.
You can also assign a macro to any other shape or object. For example, assume you’d like to execute a
macro when the user clicks a Rectangle object then draw a Rectangle object, right click on it and
choose Assign Macro from its shortcut menu and click OK.
After performing these steps, clicking the rectangle will execute the macro.
You can also execute a procedure from another procedure. Follow these steps if you want to give this a
try:
i) Activate the VBA module that holds the Hello routine.
ii) Enter this new procedure.
Sub CallSub()
Call Hello
End Sub
iii) Execute the CallSub macro.
The examples given above is not an exhaustive list. There are other ways to execute a procedure, I
hope I can explain to you in future.
Here, a formula is calculated (number to the power of ½) and then the result is assigned to the variable
SquareRoot. To tell the function what value to return, you assign that value to the name of the
function. We use SquareRoot as the function name as well.
Looks how the function is call from another procedure by entering the following simple procedure in
the same VBA module that contains the SquareRoot function:
Sub GetSub()
Ans = SquareRoot(16)
MsgBox Ans
End Sub
When this Sub is run, Excel shows a message box that contains the value of the Ans variable, which is
4.
Its very simple to call this VBA Function procedure from a worksheet formula.
Goto a worksheet in the same workbook that holds the SquareRoot function. Then enter the following
formula into any cell:
=SquareRoot(25)
You will get 5 in the cell i.e. the square root of 25
you can also use a cell reference as the argument for the SquareRoot function. For example, if cell C1
contains a value, you can enter
=SquareRoot(C1). In this case, the function returns the number obtained by calculating the square root
of the value in C1.
This function can be used as many times as you want in the worksheet. When you select the Insert-
Insert Function menu from Excel and choose the User Defined category, your custom functions also
appear in the Insert Function dialog box together with Excel’s built-in functions. As shown in Figure 5-
7, the Insert Function dialog box lists your very own function. Bravo!
7) Summary
In this Part, you learn some of the tools required to help you build a strong
programming foundation specifically, event, sub, and function procedures.
You learned how to use and build these procedures while considering the
procedure’s scope, available parameters, and return values (function
procedures).
- Looping
All programming languages contain logical constructions for controlling the sequence of
statement through a program, and VBA is no exception. When we say A > B or A = B, we
mean to say
The value of A is greater than the value of B and,
The value of A equals the value of B
The statements above will be evaluated as true or false by a computer program. Then, based on
the result of the logic, the program selects a direction in which to proceed.
Apart from this, a programming languages also use the operators AND, OR, NOT. We will
understand more on this logical operators when we look at example programs later.
Generally,
= Tests for equality
<> Tests for inequality
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
As for the AND, OR, and NOT operators, the 3 tables below illustrates the rules.
a) If / Then / Else
There are several ways to implement this code structure. The most basic uses just one line of
code.
In this example, If a condition is evaluates as true the code statement following Then will be
executed, otherwise code execution proceeds with the next statement. If you need more than
one code statement executed, then you should use the block form of If / Then and end the code
structure with End If
If (condition) Then
End If
Again, the condition must be true or the block of code statements will not execute.
The following procedure is a simple age guessing game where the user has to guess the age
entered. Three If/Then structures are used to determine what message is output to the user
depending on their guess.
Private Sub GuessAge()
Dim userGuess As Integer
Dim age As Integer
age = 25
userGuess = Val(InputBox(“Guess a number between 20 and 30.”, “Guess Age”))
If (userGuess > age) Then
MsgBox (“Too high!”)
MsgBox (“The answer is “ & age)
End If
If (userGuess < age) Then
MsgBox (“Too low!”)
MsgBox (“The answer is “ & age)
End If
If (userGuess = age) Then MsgBox (“You got it!”)
End Sub
You enter your age as 25. Then the program ask the user to enter a number using a input box.
The If/Then structures each use one condition that compares the values stored in the userGuess
and age variables. For example, if the user guess correctly, i.e. when the condition age equal
user guess is true, the message box in the If/Then structure with the true condition is executed.
If (condition)
Else
End If
The If/Then structures in the age guess procedure can also be written as follows, where
Here you see the keyword Else is used to direct the program to another block of code that is
executed if the condition (userGuess <> age) evaluates to false.
There is no limit on the number of conditions you can use with an If/Then code structure.
The condition
If (userGuess <> age) Then
can also be written as
If (userGuess < age) Or (userGuess > age) Then
When the logical operator Or is used only one of the condition evaluated as true, then the
expression returns true and the logic is maintained.
There are numerous possibilities for achieving the same logic when using If/Then/Else and
conditionals.
If x = 5 then
MsgBox “Hello”
Else
MsgBox “Goodbye”
End if
The first block of code will be executed if the condition is true, and the other block will be
executed otherwise (if x is not equal to 5).
You can also use nested the If/Then/Else code structure if you want to. The procedure below
outputs a short message to the user to show the smallest value.
The above code segment uses variable Result to hold the smallest value.
3 variables are given a value and the program will find the smallest value and outputs it to the
user. So the smallest here is 5.
Another option regarding If/Then/Else structures is the ElseIf clause. The ElseIf clause is used
like the Else clause with a conditional expression. You can use the if...then...elseif statement if
you want to select one of many blocks of code to execute: Look at the example below,
Private Sub Greeting()
Dim theHour As Integer
theHour =hour(time)
If theHour = 9 then
MsgBox("Just started...!")
elseif theHour = 11 then
MsgBox ("Hungry!")
elseif theHour = 12 then
MsgBox ("Ah, lunch-time!")
elseif theHour = 17 then
MsgBox ("Time to go home!")
else
MsgBox ("Unknown")
end if
End Sub
The first If/Then/Else structure is checking if the time of the day is between 8:00 A.M. and 5:00
P.M.
If theHour = 9 expression is true then a message box is used to display the string “Just
started…!”. (Remember that it had to be between 9:00 A.M. and 5:00 P.M. to get to this point.)
After that if theHour holds 11 then, the string “Hungry” is shown in a message box. And so on.
There is no limit to the number of ElseIf clauses that can be used and you can also nest more
If/Then/Else structures inside an ElseIf clause.
b) Select/Case
You can use many ways to accomplish the same task with If/Then/Else and ElseIf code
structures but sometimes using too many of the If/Then/Else and ElseIf statements can make it
difficult to follow the logic of your program.
An easier more efficient way is to use the Select/Case code structure in situations where you
find yourself using a large number of ElseIf statements. This is how it works: First we have a
single expression (most often a variable), that is evaluated once. The value of the expression is
then compared with the values for each Case in the structure. If there is a match, the block of
code associated with that Case is executed.
End Select
As you can see above the Select/Case structure must begin with Select Case and end with End
Select. The expression immediately following Select Case is usually a variable of numerical or
string data type.
As you can see above the Select/Case structure must begin with Select Case. Immediately after
that is the expression. This expression is a variable of numerical or string data type. The Select
Case structure end with End Select.
Next, a list of one or more code blocks is entered just below the keyword Case and a condition.
The condition is a comparison to the expression in the opening line of the structure. VBA will
run through the list until it finds a condition that evaluates as true, then executes the block of
code within that case element. Any additional case elements following one that evaluates as
true are ignored, even if their conditions are also true. The last case element should use Case
Else. This ensures that at least one block of code executes if all other conditions are false.
The following example uses a Select/Case structure in a VBA function designed to work with
an Excel spreadsheet. The input value should be numerical.
This value represents a sales volume and is passed into the function and stored in the variable
salesVolume. The variable salesVolume is used as the test expression for the
Select/Case structure.
Public Function SalesGrade(salesVolume As Single) As String
Select Case salesVolume
Case Is > 100000
SalesGrade = “Excellent”
Case 80000 To 100000
SalesGrade = “Mediocre”
Case Else
SalesGrade = “Work Harder!”
End Select
End Function
If sales volume is more than 100000 then the function will assigned the sales as “Excellent.
And sales is between 80000 to 100000 then it is “Mediocre”. Lastly if sales volume is less than
80000 then it will tell user to “Work Harder1”.
End Select
End Sub
The first case element uses Case 1 that is d =1. If this condition is evaluates as true, the
message box will show “Sleepy Sunday”
For Case 2 that is d = 2, then the message box will displays “Monday Again!” And so on. Note
that the last case element should use Case Else. This ensures that at least one block of code
executes if all other conditions are false.
2) Looping
Most of the time when you write code, you want to allow the same block of code to run a
number of times. You can use looping statements in your code to do this.
You may know how many times your program needs to loop, or variables used in your
program’s code may determine this.
a) For-Next loops
First you’ve the For-Next loop.You can use a For...Next statement to run a block of code,
when you know how many repetitions you want. Here’s the syntax for this
structure:
For count = start To end [Step stepval]
[statements]
[Exit For]
[statements]
Next [counter]
A counter variable is used to control the looping, which starts at one value and stops at another
value. The statements between the For statement and the Next statement are the statements that
get repeated in the loop.
A For-Next example
This routine loops 10 times and add all the integer from 1 to 10.
Sub SumUp()
Dim n As Integer
Dim t As Integer
For n = 1 To 10
t=t+n
Range(“A1”).Value = t
Next n
MsgBox " The total is " & t
End Sub
In this example, n (the loop counter variable) starts with a value of 1 and increases by 1 each
time through the loop. The first time through the loop, the procedure add 1 to the variable t. The
second time through (n = 2), where t = 1 and n = 2. Add them and you get t = 3. The third loop
i.e. n = 3 and t = 3. Add them, you get t = 6 and so on. In the end t will equal 55.
Using the Step keyword, you can increase or decrease the counter variable by the value you
specify. You can use a Step value to skip some values in a For-Next loop. Here’s the same
procedure as in the preceding section, rewritten to insert random numbers into every other cell:
Sub SumUp()
Dim n As Integer
Dim t As Integer
For n = 1 To 10 Step 2
t=t+n
Range(“A1”).Value = t
Next n
MsgBox " The total is " & t
End Sub
This time, n starts out as 1 and then takes on a value of 3, 5, 7, and so on.
The final n value is 9. The Step value determines how the n counter is incremented.
You can exit a For...Next statement with the Exit For keyword. When VBA encounters this
statement, the loop terminates immediately.
The example below demonstrates the Exit For statement. This routine identifies which of the
active worksheet’s cells in column B has the smallest value:
Sub ExitForHow()
Dim MinVal As Double
Dim Row As Long
MinVal = Application.WorksheetFunction. _
Min(Range(“B:B”))
Next Row
End Sub
I use the Excel’s MIN function to find the minimum value in Column B and assigns the result
to the MinVal variable. After that, the For-Next loop then checks each cell in the column. If the
cell being checked is equal to MinVal, the routine will stop and the Exit For statement will
terminates the loop.
Before the loop is terminated, the procedure activates the cell with the minimum value and
show the user of its location. Notice that I use Rows.Count in the For statement to assign the
number of rows in the worksheet.
The examples above use relatively simple loops. However, like the If/Then/Else structure you
can have any number of statements in the loop and nest For-Next loops inside other For-Next
loops.
The following example uses a nested For-Next loop to format a 10-row-x-5-column range of
cells into font bold (see Figure 6.). Please note that the routine executes the inner loop (the loop
with the Row counter) once for each iteration of the outer loop (the loop with the Col counter).
In other words, the routine executes the Cells(Row, Col) to format the font bold.
The next example uses nested For-Next loops to initialize a three-dimensional array with the
value 1. This routine executes the statement in the middle of all the loops (the assignment
statement) 1,000 times, each time with a different combination of values for a, b, and c:
Sub ArrayLoops()
Dim MyMatrix(10, 10, 10)
Dim a As Integer
Dim b As Integer
Dim c As Integer
For a = 1 To 10
For b = 1 To 10
For c = 1 To 10
MyMatrix(a, b, c) = 1
Next c
Next b
Next a
End Sub
b) Do-While loop
When you want to execute a task or a series of tasks as long as a specific condition is true, use
the Do-While loop. Here’s the Do-While loop syntax:
Do [While condition]
[statements]
[Exit Do]
[statements]
Loop
The following example uses a Do-While loop. This routine uses the active cell as a starting
point and then travels down the column, multiplying each cell’s value by 3. The loop will stop
when the routine encounters an empty cell.
Sub DoWhileNotEmpty()
Do While ActiveCell.Value <> Empty
ActiveCell.Value = ActiveCell.Value * 2
ActiveCell.Offset(1, 0).Select
Loop
End Sub
In contrast, when you need the loop instructions to execute at least, use a Do-Loop While loop.
This example performs exactly as the previous procedure but uses a different loop syntax:
Sub LoopWhileNotEmpty()
Do
ActiveCell.Value = ActiveCell.Value * 3
ActiveCell.Offset(1, 0).Select
Loop While ActiveCell.Value <> Empty
End Sub
Note the key difference between the Do-While and Do-Loop While loops:
The Do-While loop always performs its conditional test first and will not execute the
statements inside the lopp if the test is not true.
Whereas the Do-Loop While loop always performs its conditional test after the
instructions inside the loop are executed. It run at least once.
Thus, this difference can have an important effect on how your program functions.
c) Do-Until loop
The Do-Until loop structure is quite similar to the Do-While structure. The only different
between the two structures is :
In a Do-While loop, a routine continues to execute while the condition remains true.
Whereas in a Do-Untilloop, the program continue to loop until the condition is true.
The following example is the same one written for the Do-While loop but
recoded to use a Do-Until loop:
Sub DoUntilEmpty()
Do Until IsEmpty(ActiveCell.Value)
ActiveCell.Value = ActiveCell.Value * 3
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Another loop structure is the Do-Loop Until loop. The following example, which has the
same effect as the preceding procedure, demonstrates an alternate syntax for
this type of loop:
Again the reason and the difference between the Do Until -Loop and the Do-Loop Until
is the same as the Do-While-Loop discussed above. In the former, the test is performed at the
beginning of the loop and the latter the condition is tested at the end of the loop
VBA has another important type of looping – the For Each -Next loop. When you use this loop,
the statements you specify between the For and Next statements execute for each element in the
specified array or collection. For example, each workbook has a collection of worksheets (the
Worksheets collection), and a Range can consists of a few cells.
When you need to loop through each object in a collection, use the For Each-
The following example loops through each worksheet in the active workbook and put a random
number, r, in the Range(“A1”) of each worksheet:
Sub FillRandomValue()
Dim ws As Worksheet
Dim r as Integer
Note that the variable ws is an object variable that represents each worksheet in the workbook.
Actually you can use any variable name that you like to represent the worksheet.
The example that follows loops through the each cells in a range and format it in bold if it is a
positive number and left it unchange if it is negative.
Sub FormatBold()
Dim Cell As Range
You can also use the For Each-Next to loop through each chart on a worksheet.
Here’s how:
Sub FormatCharts()
This program will loop through each chart on Sheet1 and changes each chart to a line chart.
Note that cht is a variable that represents each ChartObject.
I suggest that you use the For Each-Next structure if suitable as it can run faster than the For-
Next one.
3) Summary
In this Part, I've explain to you how conditional and logic structures are used by VBA to
construct a program.
Part G: Debugging And Error-Handling Techniques
In This Part, we will learn
- Understand the different type of errors
- Trapping and handling errors
- Using the VBA on Error and Resume statements
- Finding how you can use an error to your advantage
1) Types of Errors
No matter how well you are at writing VBA code, sooner or later you will encounter an error
when running your program . For example, you may have type a keyword incorrectly or
misspell the syntax. If such an error occurred, you won’t even be able to execute the procedure
until you correct it.
When working with VBA, you should be aware of these classes of errors: compile errors, run-
time errors, design and logical errors.
a) Design errors
This error consist of syntax errors that occur when you mistype a statement. The statement
MsgBox (“Simple Error” , produces a syntax error because you have omitted the closing
parenthesis.
b) Compile errors
Compiling is the process of converting or translating the VBA code into a format that the
computer can understand. This compiling process happened very fast and you are typically
unaware of it happening.
If any errors occur during the compile process, an error message pops up, and the VBE will
highlights the location of the error.
c) Runtime errors
This error occurs when your code executes. VBE will displays a message box informing you of
the error. A common example will be the TYPE MISMATCH error when you pass the wrong
data type value to a variable. If you pass a string to an expression that expects a numeric value,
a runtime error occurs.
Generally to avoid your program stop due to runtime error you need to use the On Error
Resume Next statement at the beginning of your procedure. Try not to do this as the program
still run although there are errors. The bottom line is you still need to handle the errors.
d) Logical errors
A logical error do not produce any type of error message. Simple logical errors include
mistyping a value, placing a decimal point in the wrong place.
So, how do we handle and debug the errors. Let me show you a few methods.
You can insert break points in a procedure to stop execution at the specified line of code. This
way, you can determine whether a procedure run correctly up to a specified location. To do
this:
- activate the VBE and double click on a module to bring up the Code Window
- click on the right side of the Code Window. The break points will be highlight red
(Figure 7.1) with a red circle on the right.
- You can clear a break point by clicking it again.
- Remember to clear all break points after you complete debugging your code.
After the break points are set, the procedure executes until it reaches the specified break
point, highlight the line and stop the execution. All the variables will be updated. (see
Figure 7.2) When you place your cursor on top of the variable, a pop up statement will tell
the value. ( a yellow box )
You can continue running your code until it encounter another break point or end the
procedure. You can change the code as needed to correct the error.
( Figu
re 7.1 )
( Figure 7.2 )
You can debug your procedure by stepping through the execution of the code one line at a time.
Unlike break points, you trace the code line by line by clicking the Step Into button. How do
you do this?
- First click inside the procedure that you want to execute
- Then click on the Step Into button once. ( see Figure 7.3 )
- The line of code that was highlighted is the active line. ( see Figure 7.4 )
- Click on the Step Out option if you want to exit the procedure
( Figure 7.3 )
( Figu
re 7.4 )
As you step into the current procedure, VBE will selects and highlight the first line of code in
the procedure i.e. the Sub or Function statement. Clicking on the Step Into option will execute
the next line. The Local Window below (see Figure 7.4) updates the values of the local
variables each time there is a value change. ( this is also the same scenario if you use the break
points method described above).
Thus you can change what is necessary to fix the error. This error trapping method is very
useful if you want to amend any logical error.
This procedure asks the user for a value. It then enters the square root of that value into the
active cell.
You have enter “1q” which is wrong. The message Run-Time ‘13’ will be display. If you click
on the “Debug” button, VBA suspends the macro so you can use the debugging tools. VBA
will show you the line of code where the error occur, the highlighted line of code shown in
Figure 7.5.
( Figure 7.5 )
To improve the procedure, you have to anticipate this error and handle it more gracefully.
The procedure below will demonstrate how this On Error Resume Next work. Insert a module
and enter the following code.
Sub ErrorExample_2()
On Error Resume Next
Dim total As Integer
Dim intA As Integer
Dim intB As Integer
Dim intC As Integer
intA = Range("A1").Value
intB = Range("A2").Value
intC = Range("A3").Value
total = intA + intB + intC
MsgBox ("Total is " & total)
End Sub
(Figure 7.6)
As you can see in Figure 7.6, the value in Range(“A3”) is not an integer but the procedure
continue to execute because the On Error Resume Next is entered at the top of the program. If
there is no such statement there a runtime error Type Mismatch error will occurs as
Range(“A3”) is not an integer and nonnumeric.
With this statement, VBA skip any runtime error that occur during the execution of the
procedure and an error message does not inadvertently display on the screen. However, an error
still exists in the code and therefore the procedure does not produce the appropriate results.
This statement is very useful if you intend to develop program to be distributed to another user.
It ensure that the program that you code does not stop abruptly due to an error encounter in the
code.
There are error trapping methods to handle any potential errors where you can inform the user
anytime that an error has occur. If you want to execute specific code when an error is
encountered, you can modify the On Error statement to be On Error GoTo label
With this statement the procedure will jump to the label section of the code whenever an error
condition is encountered. Typically this label code is placed at the end of the procedure. You
need to enter an Exit Sub statement prior to the labeled section to keep the procedure from
executing the code within the label if an error is not encountered.
(Figure 7.7)
(Figure 7.8)
As promised above, I will further explain to you how to handle a runtime error. As you can see
in procedure ErrorExample_1, a runtime error 13 “Type Mismatch” has occurred.
This error is capture by Excel VBA in the Err object. You can use this information to process
the error and often correct the error situation. The number property in this Err object i.e.
Err.Number enable us to design an appropriate error processing code to react differently
depending upon the specific runtime error encountered.
We have the Run-time error 13 in the procedure i.e. the value passed to the variable intC is not
the correct data type. A string was passed instead of an integer.
If runtime error 13 is encounter in this procedure, then the message box in Figure 7.9 will be
displayed to the user and when user click the OK button, the procedure will end.
(Figure 7.9)
This is only one run time error example. There are many others but the most common one is
shown in Table 7.1 below;
(Tabl
e 7.1)
When you use an On Error statement in your VBA code, Excel will bypass its built-in error
handling and use your own error-handling code. In the previous example, a run-time error
causes macro execution to jump to the statement labeled errorHandler. As a result, you prevent
Excel’s unfriendly error messages and you can display your own friendlier message to the user
like using the Err.Number statement in the procedure ErrorExample_4.
On Error Resume Next With this statement, VBA ignores all errors
and continue to execute until end.
(Figure 7.10)
If the On Error Resume Next is not used, then there will be a runtime error 11, “Division By
Zero” as you can see Range(“A5”) has zero sales in Figure 7.10. But the procedure continue to
run ignoring this run time error as the On Error Resume Next statement already entered.
5) Summary
An error-handling routine has the following characteristics:
It starts immediately after the label specified in the On Error statement.
You must use a statement such as Exit Sub or Exit Function immediately before the
label because this error handling code will only be execute if an error occurs.
A Resume statement is use if you need to continue with the main code even though an
error has occurred.
Error handling can be a tricky proposition, after all we are only human that we can’t anticipate
them all.
Part H: VBA UserForms and ActiveX Controls
In this Part, we will examine...
- UserForms
- The Option Button Control
- The Scroll Bar Control
- The Frame Control
- The RefEdit Control
- The MultiPage Control
- The List Box and Combo Box Controls
- Using worksheet as a container
You can add ActiveX controls, such as buttons, option buttons, list boxes and so on, on
worksheets, chart sheets or userforms - not on a module. Placing controls on a userform
creates a custom dialog box. Controls on worksheets and charts have the benefit of being
closely tied to the data they use; custom dialog boxes are best when you want to use the same
set of controls with a number of different worksheets – you retain generality and extend the
ability of VBA programmers to collect user input.
These VBA objects are invaluable for adding custom user interfaces to your applications. We
have so far collect input from the user via dialog boxes using InputBox() and MsgBox()
functions. Now its time to make our office application more sophisticated and user friendly by
using the range of ActiveX controls provided by Excel VBA.
Working with user forms, for me is the most interesting and fun part of VBA application
development. When designing the form, you need to know 3 things
a) Which ActiveX controls are available.
b) How to place, resize and line up controls on a user form.
c) How to give controls properties in the Properties Window
Apart from using UserForm to interact with users, I’ll also show you how you can use a
worksheet as a control panel.
Just as you have guess, the structure of a form code window or module is the same as any
other module window. Click on the dropdown box on the upper-left corner will display all
objects contained within the form, including the UserForm object. Here you will also find a
general declarations section for making module level declarations in the form module.
Whereas the upper-right corner contains a dropdown list of all event procedures associated
with the various objects that may be contained in the form. An example code window and
properties for a form is shown in Figure 8.2.
(Fig
ure 8.2)
Generally, the behavior of variables and procedures for UserForm are identical with other
Excel objects we discussed before. The declaration statements Dim, Private, and Public
keywords in a form module are identical to that of an object module as discussed in Part C and
D. For example, the scope of variables and procedures declared as Public in the general
declarations section of a form module are global just like any other the Excel objects discussed
before.
The UserForm object has several event procedures, including Click(), Activate(), and
Initialize() among others. To view the full list of event procedures of the UserForm object,
select the UserForm object in the object dropdown list and then select the event procedure
dropdown list from the form module (see Figure 8.2). Some of these event procedures should
be familiar, as they are common to several ActiveX controls. Table 8.2 lists a few of the more
commonly used event procedures of the UserForm object.
Event Description
Activate() Triggered when the UserForm is activated
Initialize() Triggered when the UserForm is loaded.
You use the tools in the Control Toolbox to add controls to your UserForm. Just click the
desired control in the Toolbox and drag it into the dialog box to create the control. After you
add a control, you can move and resize it by using standard techniques.
When added to a form, you access the properties of an ActiveX control via the Properties
window and you access event procedures associated with ActiveX controls via the form
module that contains them. Table 8.3 shows the type of ActiveX control and what they do.
(Table 8.3)
Let’s do a simple exercise (Example A): A Label, Command button and TextBox are used.
i) From the VBE insert a form into a new VBA project.
ii) On the Properties Window, change its Caption to “Hello” (see Fig 8.3)
iii) Add a Label and CommandButton controls to the form and change their Name
properties to something meaningful like lblOutput and cmdHello (see Fig 8.4 and Fig
8.5)
iv) Change caption to “Click Me” for CommanButton and delete the Label caption.
v) Add a TextBox and name it to txtEnter.
vi) Adjust the size and appearance of all the control to suit your taste.
vii) Next double click on the CommandButton control to activate its Code Window
viii) Select the Click() event on the upper-right dropdown list.
ix) Finally enter the code below to the Click() event procedure. (see Fig 8.6)
Example A:
Private Sub cmdHello_Click()
lblOutput.Caption = “Welcome ” & txtEnter.Text
End Sub
With the above procedure, user will enter his/her name in the textbox. After that if the user
clicks the CommandButton control name cmdHello, the click event procedure is triggered,
and the Caption property of the Label control named lblOutput is changed to “Welcome”
follow by the name the user entered in the text box.(see Fig 8.7)
(Figure 8.3)
(Figure 8.4)
(Figure 8.5)
(Figure 8.6)
Note that (see Figure 8.6) on the upper-left of the dropdown list on the control module list all
the ActiveX controls added to the UserForm.
To test the application, select the form and click on Run/Sub UserForm on the VBE standard
toolbar or menu bar, or press F5 on the keyboard. The form appears as a window above the
Excel application. Click the Click Me button to output the simple message to the Label
control. To close the form, simply click on the X in the upper-right corner of the window.
(Figure 8.7)
I suggest you use these naming convention for all the controls:
i) Label = lbl
iv) ListBox = lb
v) CheckBox = chk
UserFormName.Show [Modal]
For example, the following code displays a UserForm object in Example when the Click()
event procedure of a Command Button control named cmdDisplayForm is triggered. The
Command Button control can be added on a worksheet or another form.
UserForm1.Show
End Sub
To hide a form from the user but retain programmatic control, usel the Hide() method of the
UserForm object.
UserForm1.Hide
Note that the Hide() method does not remove the UserForm object from system memory, thus
the form and its components can still be accessed programmatically. To remove a form
completely from system memory, call VBA’s UnLoad() method.
UnLoad UserForm1
There are a few more ActiveX controls that I am going to show you below.
The function of the Frame control is to groups ActiveX controls on a form especially when the
ActiveX controls grouped are related by content, or in the case of Option Button controls, be
made mutually exclusive (see Fig 8.8).
The properties of the Frame control are seldom referenced in code. We usually set the Name
and Caption properties along with a couple of appearance properties (Caption, Font, Height
etc.) at Design Time.
You rarely access the Frame control programmatically. However, Frame control are often use
to organizes or groups controls on a form for aesthetic appearance; in the case of Option
Button controls, behavior.
(Figure 8.8)
b) The Option Button Control
Option Button controls are added to the userform as a group. It is common practice that we
group all the Option Buttons with a Frame control. So no matter how many Option Button
controls are added to the form only one can be selected at any given time.
When the user selects an Option Button from a group of Option Buttons, Excel VBA will
automatically deselect a previously selected Option Button. We will look at an example below
to clarify this concept.
RefEdit control is use to enable user select a range of cells from a worksheet for some specific
task. Many Excel’s dialogs and wizards contain RefEdit controls, like the Goal Seek dialog
box shown in Figure 8.9
(Figure 8.9)
When user select a range from an existing Excel worksheet, the textual reference for the
selected range is automatically entered into the edit region of the control. You can also enter
the range manually by typing in the text area of the control.
Let’s look at an example to illustrate the combination of using the RefEdit control,
OptionButton, Label, Frame, CommandButton, TextBoxt controls.
Example B:
ii. This dialog box has nine controls. Set the properties according to Table 8.4.
TextBox 1 txtResult
Frame 1 Calculate
RefEdit rfeInput
(Table 8.4)
The next set of steps makes executing this procedure an easy task: Double-click the Calculate
button and enter the following Code:
txtResult.Value = Round(Application.Average(myRange), 2)
txtResult.Value = Application.Max(myRange)
txtResult.Value = Application.Min(myRange)
End If
End Sub
Unload UserForm3
End Sub
Double click on UserForm3, select the Initialize and enter the following code:
Worksheets("Example C").Activate
rfeInput.SetFocus
End Sub
The above code is to ensure the Worksheets("Example C") is active and the focus is on the
RefEdit control.
vi. Run the program.(Run/Sub UserForm on the VBE)
First you select a range on the worksheet. The textual reference for the selected range is
automatically entered into the edit region of the control. You can also enter the range manually
by typing in the text area of the control.
After that you select which option you want to calculate by clicking on one of the option
buttons. Finally you click on the Calculate button to start calculating. The label caption will
change to “Average” if you’ve selected the Average option button and the result is stored in
the textbox. (see Fig 8.11)
(Figure 8.11)
The List Box control shows a certain number of values in a form where the user may select
one or more items.
You can add the List Box control on the form with varying height and width such that it
displays one or more items in the list. If there are more items in the list that can be displayed in
the area provided, the scroll bars will automatically appear.
It is a good practice to draw the List Box control with its Height property set to a value large
enough for several values to be displayed, because it is difficult to see the scroll bar when the
control is at a minimum height.
If space on the form is an issue, use a Combo Box control instead and set the Style property to
dropdown list. The Combo Box control combines the features of a List Box control with a
Text Box control, allowing the user to enter a new value if desired and it also save you some
space.
The difference between a combo boxes and the list boxes is that the combo box is a drop-down
list and the user can submit a single value either one of the values from the drop-down list or
any other value. The list box shows a certain number of values with or without a scroll bar and
the user can select one or more values but not a value that is not in the list.
Properties of the List Box and Combo Box controls usually set at Design Time and Run Time
are listed in Table 8. 5). Data is added to the List Box and Combo Box controls at run time
using their AddItem() method.
ControlName.Additem (item)
Property Description
Name Sets the name of the control to use as a code reference to the object.
MultiSelect List Box control only. Indicates whether of not the user will be able to
select multiple items in the list.
Value Holds the current selection in the list. If a multi-select List Box control
is used, the BoundColumn property must be used to identify the
column from which the Value property is set.
BoundColumn Identifies the column that sets the source of the Value property in a
multi-select List Box.
ListCount Run-time only. Returns the number of items listed in the control.
ListIndex Run-time only. Identifies the currently selected item in the control.
Style Combo Box control only. Specifies the behavior of the control as a
combo box or a dropdown list box.
(Table 8.5)
The AddItem() method must be called for every row of data added to the list. A looping code
structure will often work well to complete this task (This will be demonstrated with Example
below). Other methods belonging to both the List Box and Combo Box controls include,
Clear() and RemoveItem() which remove all or one item from the control’s list, respectively.
Example C:
Add a UserForm and a ListBox named ListBox1 (shown below in Fig 8.12)
(Figure 8.12)
i. Select your UserForm and press F7 to activate the userform code window.
ii. Select the Initilize event procedure from the drop-down list at the top of the Code window.
With ListBox1
.AddItem "Boston"
.AddItem "Chicago"
.AddItem "Detroit"
.AddItem "Miami"
.AddItem "Pasadena"
.AddItem "Denver"
.AddItem "Florida"
End With
ListBox1.ListIndex = 0
End Sub
iv. To test the form, on the main menu of Visual Basic, click Run -> Run Sub/UserForm
To determine the selected item, add the following to the CommandButton1_Click procedure:
The result is display in Figure 8.13
MsgBox Msg
End Sub
(Figure 8.13)
Note : the first item in a ListBox has a ListIndex of 0, not 1
To enable the user select more than one item, you need to set the ListBox MultiSelect property
to 1. To determine all selected items, you need to use the Selected property, which contains an
array.
at run time by using adding VBA statement below to the UserForm_Initialize() event.
UserForm2.ListBox1.MultiSelect = 1.
On the VBE window, double click on CommandButton2 and enter the code below to the
CommandButton2_Click event procedure:
Dim i As Integer
UserForm2.ListBox1.MultiSelect = 2
For i = 0 To ListBox1.ListCount – 1
If ListBox1.Selected(i) Then
Msg = Msg & ListBox1.List(i) & vbNewLine
End If
Next i
MsgBox Msg
End Sub
To remove an item from the ListBox, you need to use the RemoveItem() statement. Add a
CommandButton3 and enter the code below.
i = ListBox1.ListIndex
ListBox1.RemoveItem (i)
End Sub
The above code will enable the selected item on the ListBox to be deleted or remove.
The Combo Box control also includes a DropDown() method that, when invoked, displays the
control’s list.
The most useful event procedure of the List Box and Combo Box controls is the Change()
event. Although you may find the DropButtonClick() event procedure of the Combo Box
control quite useful as well. The Change() event is triggered when the Value property of the
control changes. (The Value property of the List Box and Combo Box control is the selected
item from the list.) The DropButtonClick() event of the Combo Box control is triggered when
the controls dropdown button is clicked signaling that the user is viewing the list of items in
the control.
Be sure to check the Object Browser for a complete list of properties, methods, and events
associated with the ActiveX controls discussed in this Part.
The MultiPage Control
The MultiPage control is another example of a container control that groups or organizes
ActiveX controls. An example of the MultiPage control in the Excel application is the Options
dialog box shown in Figure 8.14 which is quite familiar to you. As you can see from this
example that the MultiPage control allows you to cram a lot of options onto a single form.
(Figure
8.14
You usuallly set their appearance at Design Time and they are rarely reference in a procedure
code. By default, when you add a MultiPage control to a form, two pages are included. To add
more pages, right click on a page tab while in Design Mode and select New Page from the
shortcut menu. Figure 8. shows a form in Design Mode containing a MultiPage control.
(Figure 8.15)
The SelectedItem property returns the currently selected Page object. It is useful for
identifying what page on the MultiPage control is active. For example:
End If
Just like the other controls you can set and manipulate Multipage in your VBA code and also
in Design Mode. Take note that there is no Activate() or Select() method of the MultiPage or
Page objects.
Therefore, you need to set the Value property of the MultiPage control to an index value
representing a specific Page object in the Pages collection object. The following statement
selects the second page (index numbers start at zero) of a MultiPage control.
MultiPage1.Value = 1
You have undoubtedly seen and used scroll bars in numerous applications for scrolling
through lengthy documents or large figures. Scroll bars sometimes automatically appear on the
sides and/or the bottom of VBA controls so the user can view the entire content displayed in a
control. Situations such as these require nothing extra from you, or your program—the scroll
bars are simply there to provide the user with a method of seeing the complete content of the
control; however,
I believe you have used scroll bars many times as a method to see the complete contents of
page or form. VBA also provides a Scroll Bar control that you can add to forms in your
project to enhance an interface, so that the user can scroll through content on a form. Apart
from this the scroll bar control also enable you to sets a value from a large range of choices.
For example in the Excel Format Cells dialog box (see Figure 8.16), a scroll is related to a
textbox for user to choose the number of decimal points
(Figure 8.16)
To do this, you need to set certain properties of the scroll during Design time (Set the Min
value and Max value in the properties window) and enter this code in the ScrollBar_Change
event.
TextBox.Value = ScrollBar.Value
The Change() event procedure is triggered when the value of the Scroll Bar control is changed
by the user i.e clicked.
Table 8.6 summarizes the major properties of the Scroll Bar control.
Property Description
Min The minimum allowed value i.e. when the scroll box is located at
its minimum location.
Max The maximum allowed value i.e. when the scroll box is located at
its maximum location.
SmallChange Ascertain the amount the value of the Scroll Bar is increase or
LargeChange Ascertain the amount the value of the Scroll Bar is is increase or
decrease when the user clicks on the Scroll Bar on either side of
the scroll box.
Value The value of the Scroll Bar as defined by range set by the Min
and Max property
(Table 8.6 )
Another common event is the Scroll() events i.e when the user drags the scroll box on the
Scroll Bar control.
Example D: Controls use are Option Button, Frame, Label and TextBox. This time we insert
all these control on a worksheet.
v) To do so, right click on the controls to activate their properties window.(see Fig
8. )
vi) Double click on the command button to activate the module window. Select the
Click() event procedure and enter this code:
Dim i As Double
Dim n As Intege
Principal = CCur(txtPrincipal.Text)
CompoundType = 12
CompoundType = 4
CompoundType = 2
Else
CompoundType = 1
End If
Periods = CInt(txtPeriods.Text)
i = IntRate / CompoundType
n = CompoundType * Periods
txtAmtEarned.Text = FormatCurrency(FutureValue)
End Sub
TextBox 1 txtPrincipal
TextBox 2 txtIntRate
TextBox 3 txtPeriods
TextBox 4 txtIntEarned
TextBox 5 txtAmtEarned
OptionButton 1 optMonth
OptionButton 2 optQuarter
OptionButton 3 optSemi
OptionButton 4 optAnnual
(Table 8.7)
(Figure 8.17)
(Figure
8.18)
First user has to enter the principal, interest rate and no. of period that need to be calculated.
Next user can choose which compound frequency that apply by selecting one of the option
buttons. Finally, click on the Calculate will start the procedure and the results will be
displayed on the interest earned and amount earned text box. (see Figure 8.18)
Example E: The Controls used and embedded on the worksheet are a ComboBox and a
SpinButton. This example will also show you, how you integrate controls and Excel built in
function i.e =PMT() used to calculate the payment for a loan based on constant payments and
a constant interest rate.
vi) Activate VBE by pressing ALT-F11, and double on the Worksheet(“Example E”)
and select the Activate event on the right-hand dropdown list.
Me.ComboBox1.Clear
Me.ComboBox1.AddItem ("None")
End Sub
Range("C9").Value = Me.SpinButton1.Value
ix) Rightclick on SpinButton1 and select Properties
Max = 10
Min = 1
SmallChange = 1
ix) Double click on ComboBox1 to bring up the Code window. Select the Change
event and enter this code:
End If
End Sub
(Figure 8.19)
When Worksheet(“Example E”) is activated, the Activate event is triggered. This will load up
the ComboBox1 with the type of cars.
When user select one of the car in the drop down list of the ComboBox1, the Change event is
triggered. The code in this procedure will execute and calculation is made. You can choose the
Length of Loan(years) by clicking the SpinButton and Range(“C9”) will be updated follow by
the calculation as well.
7) Summary:
We have learn how to use VBA UserForms and worksheets as containers
for our applications. We also discussed adding ActiveX controls to a form,
including the Label, Command Button, Text Box, Frame, Scroll Bar, Option
Button, RefEdit, MultiPage, Combo Box, and List Box controls and how to
use the code window of a form.