Excel VBA Made Easy
Excel VBA Made Easy
II
Disclaimer
Excel VBA Made Easy is an independent publication and is not affiliated with,
nor has it been authorized, sponsored, or otherwise approved by Microsoft
Corporation.
Trademarks
Microsoft, Visual Basic, Excel and Windows are either registered trademarks
or trademarks of Microsoft Corporation in the United States and/or other
countries.
Liability
The purpose of this book is to provide basic guideline for people interested in
Excel VBA programming. Although every effort and care has been taken to
make the information as accurate as possible, the author shall not be liable for
any error, harm or damage arising from using the instructions given in this
book.
ISBN: 1449959628
Copyright© Liew Voon Kiong 2009. All rights reserved. No part of this book
may be reproduced or transmitted in any form or by any means, without
permission in writing from the author.
III
Acknowledgement
I would like to express my sincere gratitude to many people who have made
their contributions in one way or another to the successful publication of this
book.
My special thanks go to my children Xiang, Yi and Xun. My daughter Xiang
edited this book while my sons Yi and Xun contributed their ideas and even
wrote some of the sample programs for this book. I would also like to
appreciate the support provided by my beloved wife Kim Huang and my
youngest daughter Yuan. I would also like to thank the million of visitors to my
VBA Tutorial website at http://www.vbtutor.net/VBA/vba_tutorial.html for
their support and encouragement.
About the Author
Dr. Liew Voon Kiong holds a bachelor degree in Mathematics(BSc), a master
degree in management (MM) and a doctoral degree in business
administration(DBA). He has been involved in programming for more than 15
years. He created the popular online Visual Basic Tutorial at www.vbtutor.net
in 1996 and since then the web site has attracted millions of visitors and it is
one of the top searched Visual Basic websites in many search engines
including Google. In order to provide more support for Excel VBA hobbyists,
he has written this book based on his online VBA tutorial at
http://www.vbtutor.net/VBA/vba_tutorial.html. He is also the author of
Visual Basic 6 Made Easy and Visual Basic 2008 Made Easy
IV
CONTENTS
Chapter 1 Introduction to Excel VBA 1
Chapter 2 Working with Variables in Excel VBA 7
Chapter 3 Using Message box and Input box in Excel VBA 16
Chapter 4 Using If….Then….Else in Excel VBA 25
Chapter 5 For……Next Loop 32
Chapter 6 Do……Loop 40
Chapter 7 Select Case.........End Select 44
Chapter 8 Excel VBA Objects Part 1–An Introduction 46
Chapter 9 Excel VBA Objects Part 2 –The Workbook Object 55
Chapter 10 Excel VBA Objects Part 3 –The Worksheet Object 60
Chapter 11 Excel VBA Objects Part 4–The Range Object 66
Chapter 12 Working with Excel VBA Controls 75
Chapter 13 VBA Procedures Part 1-Functions 86
Chapter 14 VBA Procedures Part 2-Sub Procedures 96
Chapter 15 String Handling Functions 99
Chapter 16 Date and Time Functions 102
Chapter 17 Sample Excel VBA Programs 109
Chapter 1
Introduction to Excel VBA
1.1 The Concept of Excel VBA
Among the Visual Basic for applications, Microsoft Excel VBA is the most
popular. There are many reasons why we should learn VBA for Microsoft
Excel, among them is you can learn the fundamentals of Visual Basic
programming within the MS Excel environment, without having to purchase a
copy of Microsoft Visual Basic software. Another reason is by learning Excel
VBA; you can build custom made functions to complement the built-in formulas
and functions of Microsoft Excel. Although MS Excel has many built-in
formulas and functions, they are not enough for certain complex calculations
and applications. For example, it is very dificult to calculate monthly payment
for a loan taken using Excel's built-in formulas, but it is relatively easier to
write VBA code for such calculation. This book is written in such a way that
you can learn VBA for MS Excel at your own pace.
You can write Excel VBA code in every version of Microsoft Office, including
MS Office 97, MS Office2000, MS Office2002, MS Office2003, MS Office
XP , MS Office 2007 and MS Offce 2010. By using VBA, you can build some
very powerful tools in MS Excel, including financial and scientific
applications that can perform financial calculations and programs that can
perform statistical analyses.
Figure 1.1:
Displaying Control Toolbox in MS Excel.
Figure 1.2: The Command Button in Design Mode
Now you select the command button and make sure the design button on the far
left of the control toolbox is depressed. Next, click on the command button to
launch the Visual Basic Editor. Enter the statements as shown in figure 1.3.
Let’s write out the code here:
Example 1.1
Private Sub CommandButton1_Click ()
Range (“A1:A10).Value=”Visual Basic “
Range (“C11”).Value=Range (“A11”).Value +Range (“B11”).Value
End Sub The first statement will fill up cell A1 to cell A10 with the phrase
"Visual Basic" while the second statement add the values in cell A11 and cell
B11 and then display the sum in cell C11. To run the program, you need to exit
the Visual Basic Editor by clicking the Excel button on the far left corner of the
tool bar. When you are in the MS Excel environment, you can exit the design
mode by clicking the design button, then click on the command button.
Writing Excel VBA code is almost exactly the same as writing code in Visual
Basic, which means you have to use syntaxes similar to Visual Basic.
However, there are codes specially designed for use in MS Excel, such as the
use of the object or function called Range. It is the function that specifies the
value of a cell or a range of cells in MS Excel spreadsheet. The format of
using Range is as follows:
The above example will enter the text “VBA” into cell A1 of the MS Excel
spreadsheet when the user presses the command button. You can also use
Range without the Value property, as shown in Example 1.3:
Example 1.3
Private Sub CommandButton1_Click ()
Range ("A1") = 100
End Sub
In the above example, clicking the command button with enter the value of 100
into cell A1 of the MS Excel spreadsheet. The follow example demonstrates
how to input values into a range of cells:
Example 1.4
Private Sub CommandButton1_Click ()
Range ("A1:A10") = 100 End Sub
Chapter 2
Working with Variables in Excel
VBA
2.1 The Concept of Variables
Variables are like mail boxes in the post office. The contents of the variables
change every now and then, just like the mail boxes. In Excel VBA, variables
are areas allocated by the computer memory to hold data. Like the mail boxes,
each variable must be given a name. To name a variable in Excel VBA, you
have to follow a set of rules, as follows:
a) Variable Names
The following are the rules when naming the variables in VBA It must be less
than 255 characters
No spacing is allowed
It must not begin with a number
Period is not permitted
Examples of valid and invalid variable names are displayed in Table 2.1
Table 2.1: Examples of valid and invalid variable names
Valid Name
My_Car
this year
Long_Name_Can_beUSE Group88
follows:
Dim password As String, yourName As String, firstnum As Integer.
If the data type is not specified, VBE will automatically declare the variable as
a Variant. For string declaration, there are two possible formats, one for the
variablelength string and another for the fixed-length string. For the variable-
length string, just use the same format as Example 2.1 above. However, for the
fixed-length string, you have to use the format as shown below:
Example 2.2
In this example, we declared three types of variables, namely the string, date
and currency.
Private Sub CommandButton1_Click()
YourName = "Alex"
BirthDay = "1 April 1980"
Income = 1000
Range("A1") = YourName
Range("A2") = BirthDay
Range("A3") = Income
End Sub
When Option Explicit is included in the program code, we have to delare all
variables with the Dim keyword. Any variable not declared or wrongly typed
will cause the program to popup the “Variable not defined” error message. We
have to correct the error before the program can continue to run.
Example 2.3
This example uses the Option Explicit keyword and it demonstrates how a typo
is being tracked.
Option Explicit
End Sub
The typo is YourNam and the error message ‘variable not defined” is displayed
.
Figure 2.2:
Error message due to typo error
2.3 Assigning Values to the Variables
After declaring various variables using the Dim statements, we can assign
values to those variables. The general format of an assignment is
Variable=Expression
The variable can be a declared variable or a control property value. The
expression could be a mathematical expression, a number, a string, a Boolean
value (true or false) and more. Here are some examples:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
In order to compute input from the user and to generate results in Excel VBA,
we can use various mathematical operators. In Excel VBA, except for + and -,
the symbols for the operators are different from normal mathematical
operators, as shown in Table 2.3.
In example 2.4, three variables are declared as single and another two
variables are declared as variant. Variant means the variable can hold any
numeric data type. The program computes the total and average of the three
numbers that are entered into three cells in the Excel spreadsheet.
Example 2.5
Option Explicit
Private Sub CommandButton1_Click() Dim secondName As String, yourName
As String
firstName = Cells(1,1).Value
secondName = Cells(2,1).Value
yourName = firstName + " " + secondName
Cells(3,1) = yourName
End Sub
In the above example, three variables are declared as string. The variable
firstName and the variable secondName will receive their data entered by the
user into Cells(1,1) and cells(2,1) respectively. The variable yourName will
be assigned the data by combining the first two variables. Finally, yourName is
displayed on Cells (3, 1). Performing addition on strings will result in
concatenation of the strings, as shown in figure 2.3 below. Names in A1 and
A2 are joined up and displayed in A3.
The first argument, Prompt, displays the message in the message box. The Style
Value determines what type of command button that will appear in the message
box. Table 3.1 lists the command button that can be displayed. The Title
argument displays the title of the message box.
Table 3.1: Style Values and Command Buttons Style Value Named
Constant Button Displayed 0 vbOkOnly Ok button 1 vbOkCancel Ok and
Cancel buttons 2 vbAbortRetryIgnore Abort, Retry and Ignore buttons. 3
vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo
5 vbRetryCancel Yes and No buttons
Retry and Cancel buttons
We can use the named constant in place of integers for the second argument to
make the programs more readable. In fact, VBA will automatically show a list
of named constants where you can yourMsg=MsgBox( "Click OK to
2 vbCancel
3 vbAbort
4 vbRetry
5 vbIgnore
6 vbYes
7 vbNo Cancel button Abort button Retry button Ignore button Yes button
No button
Example 3.1 In this example, the message in cell (1,2) “Your first VBA
program” will be displayed in the message box. As no named constant is
added, the message will simply display the message and the “OK” button, as
shown in Figure 3.1
MsgBox YourMsg
Figure 3.1: Message box with the OK button
Example 3.2
In this Example, the named constant vbYesNoCancel is added as the second
argument, so the message box will display the Yes, No and the Cancel buttons,
as shown in Figure 3.2.
Private Sub CommandButton1_Click()
MsgBox YourMsg,vbYesNoCancel
Figure 3.2:
Message box with the Yes, No and Cancel buttons
To make the message box looks more sophisticated, you can add an icon beside
the message. There are four types of icons available in VBE, as shown in
Table 11.3.
Table 3.3
Value Named Constant
16 vbCritical
32 vbQuestion
48 vbExclamation
64 vbInformation
Icon
Example 3.3
The code in this example is basically the same as Example 3.2, but the named
vbExclamation is added as the third argument. The two name constants can be
joined together using the “+” sign. The message box will now display the
exclamation icon, as shown in Figure 3.3.
Figure 3.3:
Message box with the exclamation icon.
You can even track which button is clicked by the user based on the returned
values shown in Table 3.2. In Example 3.4, the conditional operators
If….Then…Else are used. You do not have to really understand the program
logics yet, they will be explained in later chapter.
Private Sub CommandButton1_Click()
Dim testMsg As Integer testMsg = MsgBox("Click to Test", vbYesNoCancel +
vbExclamation, "Test Message") If testMsg = 6 Then Cells(1,1).Value = "Yes
button was clicked"
• Prompt - The message displayed in the inputbox. Title - The title of the Input
Box.•
• default-text - The default text that appears in the input field where users can
When the user clicks the OK button, the input box as shown in Figure 3.4 will
appear. Notice that the caption of the input box is "Message Entry Form" and
the prompt message is “What is your message”. After the user enters the
message and clicks the OK button, the message will be displayed in cell A1
Figure 3.4: The
input box
Chapter 4
Using If….Then….Else in Excel
VBA
Visual Basic Editor (VBE) in MS Excel is just as powerful as the stand alone
Visual Basic compiler in the sense that you can use the same commands in
programming. For example, you can use If…Then...Else structure to control
program flow in VBE that execute an action based on certain conditions. To
control the program flow, we need to use the conditional operators as well as
the logical operators, which are discussed in the following sections.
End If
* Any If...Then...Else statement must end with End If. Sometime it is not
necessary to use Else.
If firstnum<secondnum Then MsgBox “ The first number is less than the second
number” Else MsgBox “ The two numbers are equal ” End If
End Sub
In this example, the program compares the values in cells (1, 1) and cells (1,
2) and displays the appropriate comment in a message box. For example, If the
first number is less than the second number, it will show the message “The first
umber is less than the second number”, as shown in Figure 4.1.
Figure 4.1
Example 4.2
In this program, you place the command button on the MS Excel spreadsheet
and go into the VBE by clicking the button. At the VBE, key in the program
code as shown below:
End Sub
We use randomize timer and the Rnd function to generate random numbers. In
order to generate random integers between 0 and 100, we combined the Int and
Rnd functions, Int(Rnd*100). For example, when Rnd=0.6543, then
Rnd*100=65.43, and Int(65.43)=65. Using the statement cells
(1,1).Value=mark will place the value of 65 into cell(1,1).
Figure 4.2
Example 4.3
This example demonstrates the use of the Not operator. Private Sub
CommandButton1_Click() Dim x, y As Integer x = Int(Rnd * 10) + 1 y = x Mod
2 If Not y = 0 Then MsgBox " x is an odd number"
End Sub
We will demonstrate the usage of the For….Next loop with a few examples.
Example 5.1
Private Sub CommandButton1_Click()
End Sub
In this example, you place the command button on the spreadsheet then click on
it to go into the Visual Basic editor. When you click on the button , the VBA
program will fill cells(1,1) with the value of 1, cells(2,1) with the value of 2,
cells(3,1) with the value of 3......until cells (10,1) with the value of 10. The
position of each cell in the Excel spreadsheet is referenced with cells (i,j),
where i represents row and j represent column.
Figure 5.1: For….Next loop with single
step increment
Example 5.2
In this example, the step increment is used. Here, the value of i increases by 2
after each loop. Therefore, the VBA programs will fill up alternate cells after
each loop. When you click on the command button, cells (1, 1) will be filled
with the value of 1, cells (2, 1) remains empty, cells (3, 1) filled with value of
3 and etc.
Private Sub CommandButton1_Click()
End Sub
Figure 5.2: For….Next loop
with step increment
If you wish to exit the For ….Next loop after a condition is fulfilled, you can
use the Exit For statement, as shown in Example 5.3.
Example 5.3
In this example, the program will stop once the value of I reaches the value of
10.
End Sub
Figure 5.3: The output of Example 5.3
In previous examples, the For…Next loop will only fill up values through one
column or one row only. To be able to fill up a range of values across rows
and columns, we can use the nested loops, or loops inside loops. This is
illustrated in Example 5.4.
Example 5.4
End Sub
In this example, when i=1, the value of j will iterate from 1 to 5 before it goes
to the next value of i, where j will iterate from I to 5 again. The loops will end
when i=10 and j=5. In the process, it sums up the corresponding values of i and
j. The concept can be illustrated in the table below:
j12345i
1 (1, 1) (1, 2) (1, 3) (1, 4) (1, 5) 2 (2, 1) (2, 2) (2, 3) (2, 4) (2, 5) 3 (3, 1) (3, 2) (3, 3) (3, 4) (3, 5) 4 (4, 1) (4,
2) (4, 3) (4, 4) (4, 5) 5 (5, 1) (5, 2) (5, 3) (5, 4) (5, 5) 6 (6, 1) (6, 2) (6, 3) (6, 4) (6, 5) 7 (7, 1) (7, 2) (7, 3) (7,
4) (7, 5) 8 (8, 1) (8, 2) (8, 3) (8, 4) (8, 5) 9 (9, 1) (9, 2) (9, 3) (9, 4) (9, 5) 10 (10, 1) (10, 2) (10, 3) (10, 4)
(10, 5)
This is a simple VBA counter that can count the number of passes and the
number of failures for a list of marks obtained by the students in an
examination. The program also differentiates the passes and failures with blue
and red colors respectively. Let’s examine the code below:
End Sub
In this example, the program will keep on adding 1 to the preceding counter
value as long as the counter value is less than 10. It displays 1 in cells (1,1), 2
in cells(2,1)….. until 10 in cells (10,1).
Do Until counter = 10
counter = counter + 1
Cells(counter, 1) = 11 - counter Loop End Sub Private Sub
CommandButton1_Click ()
Examle 6.3
Private Sub CommandButton1_Click() Dim counter , sum As Integer 'To set the
alignment to center Range("A1:C11").Select With Selection
.HorizontalAlignment = xlCenter End With
End Sub
In the following example, the program will process the grades of students
according to the marks given.
Example 7.1
End Sub
Chapter 8 Excel VBA Objects Part
1–An Introduction
8.1: Objects
Most programming languages today deal with objects, a concept called object
oriented programming. Although Excel VBA is not a truly object oriented
programming language, it does deal with objects. VBA object is something like
a tool or a thing that has certain functions and properties, and can contain data.
For example, an Excel Worksheet is an object, a cell in a worksheet is an
object, a range of cells is an object, the font of a cell is an object, a command
button is an object, and a text box is an object and more.
In order to view the VBA objects, you can insert a number of objects or
controls into the worksheet, and click the command button to go into the code
window. The upper left pane of the code window contains the list of objects
you have inserted into the worksheet; you can view them in the dropdown
dialog when you click the down arrow. The right pane represents the events
associated with the objects.
An Excel VBA object has properties and methods. Properties are like the
characteristics or attributes of an object. For example, Range is an Excel VBA
object and one of its properties is value. We connect an object to its property
by a period (a dot or full stop). The following example shows how we connect
the property value to the Range object.
Example 8.1
In this example, by using the value property, we can fill cells A1 to A6 with
the value of 10. However, because value is the default property, it can be
omitted. So the above procedure can be rewritten as
Example 8.2
Private Sub CommandButton1_Click()
Range("A1:A6")= 10
End Sub
Cell is also an Excel VBA object, but it is also the property of the range
object. So an object can also be a property, it depends on the hierarchy of the
objects. Range has higher hierarchy than cells, and interior has lower hierarchy
than Cells, and color has lower hierarchy than Interior, so you can write
Range("A1:A3").Cells(1, 1).Interior.Color = vbYellow
This statement will fill cells (1, 1) with yellow color. Notice that although the
Range object specifies a range from A1 to A3, but the cells property specifies
only cells(1,1) to be filled with yellow color, it sort of overwrites the range
specified by the Range object.
Font is an object which belongs to the Range object. Font has its own
properties. For example, Range(“A1:A4”).Font.Color=vbYellow , the color
property of the object Font will fills all the contents from cell A1 to cell A4
with yellow color.
Count is also a property of the Range object. It shows the number of cells in
the specified range. For example, Range (“A1:A10”).Count will return a value
of 10. In order to display the number of cells returned, you can write the
following code.
Example 8.3
Private Sub CommandButton1_Click()
End Sub
8.2.2 Methods
Besides having properties, Excel VBA objects also have methods. Methods
normally do something or perform certain operations. For example,
ClearContents is a method of the range object. It clears the contents of a cell
or a range of cells. You can write the following code to clear the contents:
Example 8.4
End Sub
In order to clear the contents of the entire worksheet, you can use the following
code:
Sheet1.Cells.ClearContents
However, if you only want to clear the formats of an entire worksheet, you can
use the following syntax:
Sheet1.Cells.ClearFormats
To select a range of cells, you can use the Select method. This method selects a
range of cells specified by the Range object. The syntax is
Range(“A1:A5”).Select
Example 8.6: The code to select a range of cells
Private Sub CommandButton1_Click() Range("A1:A5").Select This example
allows the user to specify the range of cells to be selected.
Private Sub CommandButton1_Click()
End Sub
To deselect the selected range, we can use the Clear method.
Range(“CiRj:CmRn”).Clear
Example 8.8
In this example, we insert two command buttons, the first one is to select the
range and the second one is to deselect the selected range.
Another very useful method is the Autofill method. This method performs an
autofill on the cells in the specified range with a series of items including
numbers, days of week, months of year and more. The format is
Example 8.9:
In this example, the source range is A1 to A2. When the user clicks on the
command button, the program will first fill cell A1 with 1 and cell A2 will 2,
and then automatically fills the Range A1 to A10 with a series of numbers from
1 to 10. Private Sub CommandButton1_Click()
End Sub
In this example, when the user clicks on the command button, the program will
first fill cell A1 with “Monday” and cell A2 wilh “Tuesday”, and then
automatically fills the Range A1 to A10 with the days of a week.
Example 8.11
This example allows the user to select the range of cells to be automatically
filled using the Autofill method. This can be achieved with the use of the
InputBox. Since each time we want to autofill a new range, we need to clear
the contents of the entire worksheet using the Sheet1.Cells.ClearContents
statement.
Private Sub CommandButton1_Click() Dim selectedRng As String
Sheet1.Cells.ClearContents selectedRng = InputBox("Enter your range")
Range("A1") = 1 Range("A2") = 2 Range("A1:A2").AutoFill
Destination:=Range(selectedRng)
Chapter 9 Excel VBA Objects Part 2
–The Workbook Object
In the previous chapter, we have learned about Excel VBA objects and their
properties and methods. In this chapter, we shall learn specifically about the
Workbook object as it is one of the most important Excel VBA objects. It is
also at the top of the hierarchy of the Excel VBA objects. We will deal with
properties and methods associated the Workbook object.
When we write VBA code involving the Workbook object, we use Workbooks.
The reason is that we are dealing with a collection of workbooks most of the
time, so using Workbooks enables us to manipulate multiple workbooks at the
same time.
When will deal with multiple workbooks, we can use indices to denote
different workbooks that are open, using the syntax Workbooks (i), where i is
an index. For example, Workbooks (1) denotes Workbook1, Workbooks (2)
denotes Workbook2 and more.
Example 9.2
Or
Figure 9.3
9.2 The Workbook Methods
There are a number of methods associated with the workbook object. These
methods are Save, SaveAs, Open, Close and more.
Example 9.4
In this example, when the user clicks on the command button, it will open up a
dialog box and ask the user to specify a path and type in the file name, and then
click the save button, not unlike the standard windows SaveAs dialog, as
shown in Figure 9.5.
End Sub
Figure 9.4: The SaveAs dialog
Another method associated with the workbook object is open. The syntax is
Workbooks.Open ("File Name")
Example 9.5
In this example, when the user click on the command button, it wil open the file
workbook_object1.xls under the pathC:\Users\liewvk\Documents\
The close method is the command that closes a workbook. The syntax is
Workbooks (i).Close
Example 9.6
In this example, when the user clicks the command button, it will close
Workbooks (1).
Similar to the Workbook Object, the Worksheet has its own set of properties
and methods. When we write VBA code involving the Worksheet object, we
use Worksheets. The reason is that we are dealing with a collection of
worksheets most of the time, so using Worksheets enables us to manipulate
multiple worksheets at the same time.
Some of the common properties of the worksheet are name, count, cells,
columns, rows and columnWidth.
Example 10.1
The above example will cause a pop-up dialog that displays the worksheet
name as sheet 1, as shown below:
Figure 10.1
The count property returns the number of worksheets in an opened workbook.
Example 10.2
Private Sub CommandButton1_Click()
MsgBox Worksheets.Count End Sub
The output is shown in Figure 10.2.
Figure 10.2
Example 10.3
The count property in this example will return the number of columns in the
worksheet.
Figure 10.3
Example 10.4
The count property in this example will return the number of rows in the
worksheet.
Figure 10.4
10.2 The Worksheet Methods
Some of the worksheet methods are add, delete, select, SaveAs, copy, paste
and more.
Example 10.5
In this example, when the user clicks the first command button, it will add a
new sheet to the workbook. When the user clicks the second command button,
it will delete the new worksheet that has been added earlier.
Example 10.6
The select method associated with worksheet let the user select a particular
worksheet. In this example, worksheet 2 will be selected.
Private Sub CommandButton1_Click()
‘Worksheet 2 will be selected Worksheets(2).Select End Sub
The select method can also be used together with the Worksheet’s properties
Cells, Columns and Rows as shown in the following examples.
‘Cell A1 will be selected Worksheets (1).Cells (1).Select End Sub
Example 10.6
Private Sub CommandButton1_Click() ‘Column 1 will be selected Worksheets
(1).Columns (1).Select End Sub
Example 10.7
Private Sub CommandButton1_Click() ‘Row 1 will be selected Worksheets
(1).Rows (1).Select End Sub
Excel VBA also allows us to write code for copy and paste. Let’s look at the
following Example:
End Sub
As an Excel VBA object, the range object is ranked lower than the worksheet
object in the hierarchy. We can also say that worksheet is the parent object of
the range object. Therefore, the Range object also inherits the properties of the
worksheet object. Some of the common properties of the range object are
Columns, Rows, Value and Formula
There are many Range properties that we can use to format the font in Excel.
Some of the common ones are Bold, Italic, Underline, Size, Name, FontStyle,
ColorIndex and Color. These properties are used together with the Font
property.
The Bold, Italic, Underline and FontStyle properties are used to format the font
style. The syntax for using Bold, Italic and Underline are similar, as shown
below:
The FontStyle property can actually be used to replace all the properties above
to achieve the same formatting effects. The syntax is as follows:
End Sub
The Font and ColorIndex properties are used together to format the font color.
You can also use the color property to display the font color,
Example 11.2
.In this example, the font color will be displayed in green (Corresponding with
ColorIndex =4):
Range("A4:B10").Font.Color = VbRed
Example 11.2
Private Sub CommandButton1_Click() Range("A1:B3").Columns(3).Formula
= "=A1+B1"
End Sub
In this example, the formula A1+B1 will be copied down column 3 (column C)
from cell C1 to cell C3. The program automatically sums up the corresponding
values down column A and column B and displays the results in column C, as
shown in Figure 11.1.
Figure 11.1
The above example can also be rewritten and produces the same result as
below:
Range("A1:B3").Columns(3).Formula = "=Sum(A1:B1)"
There are many formulas in Excel VBA which we can use to simplify and
speed up complex calculations. The formulas are categorized into Financial,
Mathematical, Statistical, Date ,Time and others. For example, in the statistical
category, we have Average (Mean), Mode and Median
Example 11.3
In this example, the program computes the average of the corresponding values
in column A and column B and displays the results in column C. For example,
the mean of values in cell A1 and Cell B1 is computed and displayed in Cell
C1. Subsequent means are automatically copied down Column C until cell C3.
In this example, the program computes the mode for every row in the range
A1:E4 and displays them in column F. It also makes the font bold and red in
color, as shown in Figure 11.2.
In this example, the program computes the median for every row in the range
A1:E4 and displays them in column F. It also makes the font bold and red in
color, as shown in Figure 11.3.
The range methods allow the range object to perform many types of operations.
They enable automation and perform customized calculations that greatly speed
up otherwise time consuming work if carried out manually.
There are many range methods which we can use to automate our works. Some
of the methods are Autofill, Clear, ClearContents, Copy, cut, PasteSpecial, and
Select.
11.2.1 Autofill Method
Example 11.7
End Sub
11.2.2 Select, Copy and Paste Methods
We use the Select method to select a specified range, copy the values from that
range and then paste them in another range, as shown in the following example:
Example 11.9
End Sub *We can also use the Cut method in place of Copy in the above
example.
11.2.2 Copy and PasteSpecial Methods
The Copy and the PasteSpecial methods are performed together. The copy
method will copy the contents in a specified range and the PasteSpecial
method will paste the contents into another range. However, unlike the paste
method, which just pastes the values into the target cells, the PasteSpecial
method has a few options. The options are PasteValues, PasteFormulas,
PasteFormats or PasteAll. The PasteValues method will just paste the values
of the original cells into the targeted cells while the PasteFormulas will copy
the formulas and update the values in the targeted cells accordingly.
Example 11.10
End Sub
The output is displayed in Figure 11.4. The original values are pasted to the
range D1:D2 while the formula is updated in the range E1:E2 but not the
formats. The original formats for the font are bold and red. The formats are
reflected in range F1:F2 but the formulas were not pasted there. Lastly,
everything is copied over to the range G1:G2.
Figure 11.4
We can also modify the code above and paste them according to the Paste
Values option and the Paste Formulas option, as shown in Example 11.10.
Example 11.11
The Check box is a very useful control in Excel VBA. It allows the user to
select one or more items by checking the checkbox or checkboxes concerned.
For example, you may create a shopping cart where the user can click on
checkboxes that correspond to the items they intend to buy, and the total
payment can be computed at the same time.
One of most important properties of the check box is Value. If the checkbox is
selected or checked, the value is true, whilst if it is not selected or unchecked,
the Value is False.
The usage of check box is illustrated in Example 12.1
Example 12.1
In this example, the user can choose to display the sale volume of one type of
fruits sold or total sale volume. The code is shown in next page.
Private Sub CommandButton1_Click() If CheckBox1.Value = True And
CheckBox2.Value = False
Then MsgBox "Quantity of apple sold is” & Cells (2, 2).Value ElseIf
CheckBox2.Value = True And CheckBox1.Value = False Then MsgBox
"Quantity of orange sold is " & Cells(2, 3).Value Else MsgBox "Quantity of
Fruits sold is” & Cells (2, 4).Value End If
The Text Box is the standard Excel VBA control for accepting input from the
user as well as to display the output. It can handle string (text) and numeric
data but not images.
Example 12.2
In this example, we inserted two text boxes and display the sum of numbers
entered into the two textboxes in a message box. The Val function is used to
convert string into numeric values because the textbox treats the number
entered as a string. Private Sub CommandButton1_Click ()
MsgBox "The Sum of " & x & " and " & y & " is " & z
End Sub
Figure 12.3: Text Boxes
12.3 Option Button
The option button control also lets the user selects one of the choices.
However, two or more option buttons must work together because as one of the
option buttons is selected, the other option button will be deselected. In fact,
only one option button can be selected at one time. When an option button is
selected, its value is set to “True” and when it is deselected; its value is set to
“False”.
Example 12.3
This example demonstrates the usage of the option buttons. In this example, the
Message box will display the option button selected by the user. The output
interface is shown in Figure 12.4.
The function of the List Box is to present a list of items where the user can
click and select the items from the list. To add items to the list, we can use the
AddItem method.
To clear all the items in the List Box, you can use the Clear method. The usage
of Additem method and the Clear method is shown Example 12.6.
For x = 1 To 10
ListBox1.Clear
Next
End Sub
Figure 12.7
12.5 Combo Box
The function of the Combo Box is also to present a list of items where the user
can click and select the items from the list. However, the user needs to click on
the small arrowhead on the right of the combo box to see the items which are
presented in a drop-down list. In order to add items to the list, you can also use
the AddItem method.
ComboBox1.Clear
Figure 12.8
12.6 Toggle Button
Toggle button lets the user switches from one action to another alternatively.
When the Toggle button is being depressed, the value is true and when it is not
depressed, the value is false. By using the If and Else code structure, we can
thus switch from one action to another by pressing the toggle button repeatedly.
Example 12.8
In this example, the user can toggle between apple and orange as well as font
colors.
Else
Cells (1, 1) = "Orange"
Cells (1, 1).Font.Color = vbBlue
End If
Chapter 13 VBA Procedures Part 1-
Functions
13.1 The Concept of Functions
There are two types of Excel VBA functions; the built-in functions and the
userdefined functions. We can use built-in functions in Excel for automatic
calculations. Some of the Excel VBA built-in functions are Sum, Average, Min
(to find the minimum value in a range), Max (To find the maximum value in a
range), Mode, Median and more. However, built-in functions can only perform
some basic calculations, for more complex calculations, user-defined functions
are often required. User-defined functions are procedures created
independently from the event procedures. A Function can receive arguments
passed to it from the event procedure and then return a value in the function
name. It is usually used to perform certain calculations.
Example 13.1
In this example, we create a function to calculate the area of a rectangle. It
comprises two arguments, one of them is to accept the value of width and the
other is to accept the value of height. Note that the function Area_Rect is called
from the event procedure (clicking the command button) and the values to be
passed to the arguments are enclosed in the parentheses.
Now, you can return to the Excel spreadsheet and enter the function in any cell.
In this Example, the function is entered in cell C1 and the values of width and
height are entered in cell A1 and cell B1 respectively. Notice that the value of
area is automatically calculated and displayed in cell C1.
Figure 13.4
The formula can be copied and updated to other cells by using the autofill
method, i.e. by dragging the place holder on the bottom right corner of the cell,
as shown in Figure 13.5 below.
Figure 13.5: using autofill method to update the formula.
The user-defined function not only calculates numerical values, it can also
return a string, as shown in Example 13.2 below:
Example 13.2
This program computes the grades of an examination based on the marks
obtained. It employed the Select Case…….End Select code structure. The
code is shown on next page.
Function grade(mark As Single) As String
grade = "E"
Case 30 To 39
grade = "D" Case 40 To 59
grade = "C" Case 60 To 79
grade = "B" Case 80 To 100 grade = "A" Case Else
In the Excel spreadsheet environment, key in the marks in column A and key in
the grade function in column B. Notice that the grades will be automatically
updated in column B as marks are entered or updated in column A, as shown in
Figure 13.6
End Function
After creating the Comm Function, we can then enter the sales volume in one
column and enter the formula based on the function Comm in another column.
The commissions will be automatically computed and updated accordingly.
Figure 13.7
13.4 Passing variables by reference and by Value in a Function
Example 13.4
Private Sub CommandButton1_Click()
A Sub procedure begins with a Sub statement and ends with an End Sub
statement. The program structure of a sub procedure is as follows:
In this example, a sub procedure ResizeFont is created to resize the font in the
range if it fulfills a value greater than 40. There are two parameters or
arguments associated with the sub procedure, namely x for font size and Rge
for range. This sub procedure is called by the event procedure Sub
CommandButton1_Click () and passed the values 15 to x (for font size) and
Range (“A1:A10”) to Rge (for range) to perform the task of resizing the font to
15 for values>40 in range A1 to A10.
Sub ResizeFont(x As Variant, Rge As Range) Dim cel As Range For Each cel
In Rge
Example 14.2
End Sub Sub ResizeFont(x As Variant, Rge As Range) Dim cel As Range For
Each cel In Rge If cel.Value > 40 Then cel.Font.Size = x
15.1 InStr
InStr is a function that looks for the position of a substring in a phrase. InStr
(phrase,"ual") will find the substring "ual" from "Visual Basic" and then return
its position; in this case, it is fourth from the left.
15.2. Left
Left is a function that extracts characters from a phrase, starting from the left.
Left (phrase, 4) means four characters are extracted from the phrase, starting
from the leftmost position.
15.3. Right
Right is a function that extracts characters from a phrase, starting from the
Right. Right (phrase, 5) means 5 characters are extracted from the phrase,
starting from the rightmost position.
15.4. Mid
Mid is a function that extracts a substring from a phrase, starting from the
position specified by the second parameter in the bracket. Mid (phrase, 8, 3)
means a substring of three characters are extracted from the phrase, starting
from the 8th position from the left.
15.5. Len
Len is a function that returns the length of a phrase.
Example 15.1
In this example, we insert five command buttons and change the names to
cmdInstr, cmdLeft, cmdRight, cmdLeft, cmdMid and cmdLen respectively.
Cells (4, 1) = InStr (phrase, "ual") End Sub Private Sub cmdLeft_Click ()
Dim phrase As String phrase = Cells (1, 1).Value Cells (2, 1) = Left (phrase,
4)
End Sub Private Sub cmdLen_Click () Dim phrase As String phrase = Cells (1,
1).Value Cells (6, 1) = Len (phrase) End Sub
phrase = Cells (1, 1).Value Cells (3, 1) = Right (phrase, 5) End Sub
Figure 15.1: The end results after clicking all the command buttons.
Chapter 16
Date and Time Functions
Excel VBA can be programmed to handle Date and Time, adding extra
capabilities to time and date handling by MS Excel. We can use various built-
in date and time handling functions to program Excel VBA date and time
manipulating programs.
The Now () function returns the current date and time according to your
computer’s regional settings. We can also use the Format function in addition
to the function Now to customize the display of date and time using the
syntaxFormat (Now, “style
argument”). The usage of Now and Format functions are explained in the table
below:
Table 16.1: Various Date and Time Formatting with Different Style
Arguments
Cells (7, 1).Value = Format (Now, "mmmm") Cells (8, 1).Value = Format
(Now, "y") Cells (9, 1).Value = Format (Now, "yyyy")
End Sub
Output
Current date and time
Day part of the current date
Weekday of the current week in numeric form. Weekday name of the current
date
Month of the current year in numeric form Full name of the current month
Current year in long form
Example 16.2
End Sub
Example 16.3
End Sub
Figure 16.3: DatePart Function
16.4 Adding and Subtracting Dates
Dates can be added using the DateAdd function. The syntax of the DateAdd
function is
DateAdd (interval, value to be added, date)
Where interval=part of date to be added. For example,DateAdd (“yyyy”, 3,
Now) means 3 years will be added to the current year. Similarly, Dates can be
subtracted using the DateDiff function. The syntax of the DateDiff function is
DateDiff (interval, first date, second date)
aforementioned functions use the argument “s” for second, “n” for minute, “h”
for hour, “d” for day,”w” for week, “m” for month and “yyyy” for year.
Example 16.4
Private Sub CommandButton1_Click ()
Body Mass Index (BMI) is so popular today that it has become a standard
measure for our health status. If your BMI is too high, it means you are
overweight and would likely face a host of potential health problems
associated with high BMI, such as hypertension, heart diseases, diabetics and
many others. The formula for calculating BMI is
BMI=weight / (height)2
The Excel VBA code for BMI calculator is illustrated below:
End Sub The function Round is to round the value to a certain decimal places.
It takes the format Round(x, n), where n is the number to be rounded and n is
the number of decimal places. The second part of the program uses the
If...Then…. Else statement to evaluate the weight level. The output is shown in
Figure 17.1
Figure 17.1: BMI
Calculator
17.2: Financial Calculator
This is an Excel VBA program that can calculate monthly payment for the loan
taken from the bank. The formula to calculate periodic payment is shown
below, where PVIFA is known as present value interest factor for an annuity.
Payment=Initial Principal/PVIFA,
The formula to compute PVIFA is
1/i - 1/i (1+i)n
End Sub
The above financial VBA calculator can also be programmed using the built-in
worksheet function, PMT. It is very much easier to program than the previous
one. The format of this function is
WorksheetFunction.pmt (rate, N, amount)
Where rate is the interest rate, N is the period of payments (of number of
periodic payments) and amount is the amount borrowed.
People usually key in the annual interest rate as an integer rather than in
decimal form, so we need to divide the rate by 100 and then divide again by 12
to get the monthly rate.
The negative sign is placed in front of the amount borrowed because this is the
amount the borrower owed the financial institute,. If we don't put the negative
sign, the payment will have a negative sign.
End Sub
Figure 17.2: Financial
Calculator
17.3: Investment Calculator
In order to get one million dollars in the future, we need to calculate the initial
investment based on the interest rate and the length of a period, usually in
years. The formula is
End Sub This Excel VBA program will test whether a number entered by the
user is a prime number or not. Prime number is a number that cannot be
divided by other numbers other than itself, it includes 2 but exclude 1 and 0
and all the negative numbers.
Figure 17.3: Investment Calculator
17.4: Prime Number Tester
In this program, we use the Select Case ......End Select statement to determine
whether a number entered by a user is a prime number or not. For case 1, all
numbers that are less than 2 are not prime numbers. In Case 2, if the number is
2, it is a prime number. In the last case, if the number N is more than 2, we
divide this number by all the numbers from 3,4,5,6,........up to N-1, if it can be
divided by any of these numbers, it is not a prime number, otherwise it is a
prime number. We use the Do......Loop While statement to control the program
flow. Besides, we also used a tag="Not Prime' to identify the number that is
not prime, so that when the routine exits the loop, the label will display the
correct answer. Below is the code:
Select Case N Case Is < 2 MsgBox "It is not a prime number" Case Is = 2
MsgBox "It is a prime number" Case Is > 2 D = 2 Do If N / D = Int(N / D)
Then MsgBox "It is not a prime number" tag = "Not Prime" Exit Do End If D =
D + 1 Loop While D <= N - 1
If tag <> "Not Prime" Then MsgBox "It is a prime number" End If End Select
End Sub
17.5 Selective Summation
This is an Excel VBA program that can perform selective summation according
to a set of conditions. For example, you might just want to sum up those figures
that have achieved sales target and vice versa. This VBA program can sum up
marks that are below 50 as well as those marks which are above 50.
In this program, rng is declared as range and we can set it to include certain
range of cells, here the range is from A1 to A10.
Then we used the For .......Next loop to scan through the selected range
rng.Cells(i).Value read the value in cells(i) and then passed it to the variable
mark.
To do selective addition, we used the statement Select Case....End Select
Finally, the results are shown in a message box
Here is the code:
Private Sub CommandButton1_Click ()
End Select Next i MsgBox "The sum of Failed marks is" & Str(sumFail) &
vbCrLf & "The sum of Passed marks is" & Str(sumPass)
End Sub