You are on page 1of 116

Learn Excel VBA Programming In 8 Easy Lessons

Table of Contents
Lesson 1 : Introduction To Excel VBA p/g 2

Lesson 2 : Making A Macro Do Simple Task p/g 12

Lesson 3 : Excel Collection Objects And Objects p/g 19

Lesson 4 : Variables And Data Types p/g 35

Lesson 5 : Sub; Event And Function Procedures p/g 48

Lesson 6 : Control Logic And Loops p/g 60

Lesson 7 : Debugging And Error-Handling Techniques p/g 75

Lesson 8 : VBA UserForms and ActiveX Controls p/g 88

1
Lesson 1 : Introduction To Excel VBA

In this Lesson, you will learn …

why use Excel VBA

the Visual Basic Editor

The purpose of this course is to show Excel users how to use the Visual Basic For
Application programming language that comes free with MS Excel. This tool will
help you to significantly enhance the power of the world’s most popular spreadsheet.
Using VBA, however, involves programming, simple but very powerful.

Nowadays computer programming has become much easier, and even so-called
normal people now engage in this activity. Programming simply means developing
instructions that the computer automatically carries out.

Excel programming means that you can instruct Excel to automatically do things that
you normally do manually — saving you lots of time resources.

Since you’re reading this, it’s a safe bet that you need to become an Excel
programmer. This could be something you initiated or you want to make yourself
more marketable. In this online course, we will learn about Excel programming so
that by the time you finish this course, you can honestly say, “Oh, Excel programming
is so easy.”

At the end of this course, we will also learn develop a few simple applications with
Excel VBA.

Before learning how to program in VBA, you have to learn how to use the software
required for creating your projects. The VBA development software is included with
each component of the Microsoft Office suite of programs, including Excel. Starting
the VBA development software places you in the VBA programming environment
IDE, which provides you with a number of tools for use in the development of your
project.

1) What is Visual Basic Editor?

You have use workbooks, formulas, charts, and other Excel goodies most of the time.
Now it’s time to expand your horizons and explore an entirely new aspect of Excel:
the Visual Basic Editor (VBE). In this chapter, you find out how to work with the
VBE, and get down to the task of writing some VBA code.

The Visual Basic Editor is a separate application where you write and edit your VBA
macros. It works seamlessly with Excel. You can activate the VBE by pressing

2
Alt+F11 when Excel is active or by using the Tool-Macro-Visual Basic Editor
command.(Fig-1.1)

To return to Excel, press Alt+F11 again.

Figure 1.1

(a) Menu Bar

Just like any other program menu bar that you have used, the VBE menu bar contains
various commands and components. You can use this commands and components in
the VBE to do things. Many of the menu commands have shortcut keys associated
with them.

Figure 1.2

Figure 1.2 is the VBE program window. There are a few components on this window.

3
(b) Project Explorer

Figure 1.3

The Project Explorer window displays a tree diagram that shows every workbook
currently open in Excel (including add-ins and hidden workbooks). When you’re
working in the VBE, each Excel workbook and add-in that’s open is a project. You
can think of a project as a collection of objects arranged as an outline. Click on the
plus sign (+) at the left of the project’s name in the Project Explorer window to
expand a project.

(c) Code Window

The VBA code is contains in the Code window (Figure 1.4, sometimes known as a
Module window). Every object in a project has an associated Code window. Double-
click the object in the Project Explorer window to bring up the Code Window. For
example, to view the Code window for the Sheet1 object, double-click Sheet1 in the
Project Explorer window. Unless you’ve added some VBA code, the Code window
will be empty.

4
Figure 1.4

(d) Object Browser

The VBE includes another tool, known as the Object Browser (Figure 1.5). This tool
allows you browse through the objects available to you. To access the Object
Browser, press F2 when the VBE is active (or choose View ➪ Object Browser). You
see a window like the one shown in Figure 1.5.

The drop-down list at the top contains a list of all currently available object libraries.
Figure 1.5 shows All Libraries. If you want to browse through Excel’s objects, select
Excel from the drop-down list.

5
Figure 1.5

(e) Properties Window

Figure 1.6

6
Figure 1.6 show the Properties window of the CommandButton1.For example when
you change the Caption property to of CommandButton1 to “Click Me” and then
notice how the new caption is displayed on the control. You can also play with some
of the other properties such as Font, Height, BackColor, Width, and Height to change
the appearance of CommandButton1.

For users of Excel 2007 ONLY, they need to install VBA for Excel 2007 from
your Office CD. Users of earlier versions of Excel need not do so.

In the new version of Excel in 2007 the user needs to install VBA for Excel to be able
to develop, maintain or modify macros.

This is the steps on how to do it :

i.. Click on the "Start" button at the bottom of your screen and chose "Control Panel"
then "Add or Remove Programs"

ii. Select "Microsoft Office" from the list of programs and click on “Change”

7
iii. Select "Add or Remove Features" and click on "Continue"

iv. Expand "Office Shared Features" with the + sign

8
v. Select "VBA for Application" and click on "Continue"

9
vi. After the installation you can now use VBA for Excel 2007.

vii. Next you need to show the "Developer" item on your toolbar. To do so click on
the Office button: , and then click the Excel Options button. In the Popular
category, select the Show Developer tab in the Ribbon check box from the options
that appear and then click OK.

10
Now click the Developer tab in the ribbon to see the Visual Basic button in the Code
group.

Note: You can switch back and forth between workbook environment and the Visual
Basic Editor (VBE) environment with the Alt+F11 combination or with the
application tabs at the bottom of the Windows screen.

You should now see a new item on your Excel menu bar "Developer" and you can
develop macros when you are ready.

viii. Lastly, set the security level of Excel so that you can use macros. To do so, click
on the "Developer" menu item and click on the "Macro Security" button in the ribbon.
Check the second level "Disable all Macros with Notification" and you are set.

3) Summary:

I hope that in this lesson, you did get a basic introduction to the VBA programming
environment. So, you’ve learn how to access the VBA IDE and how to view and use
some of its major components.

11
Lesson 2 : Making A Macro Do Simple Task

In this Lesson, you’ll learn to…

record a macro

automate a task

1) Recording Your First Macro

You can use Excel build-in macro recorder to translate your actions into VBA macro
commands. After you recorded the macro, you will be able to see the VBA code in the
Module window. Before you record a macro, plan the steps and commands that you
want the macro to perform. Every action that you take during the recording of the
macro will be recorded - including the correction that you made.

In this example, we will record a macro that sets the cell background color to light
yellow. To record the macro, follow the steps below;

a) Select a Range on a Worksheet and then select Record New Macro...under


Tools...Macro (shown in Fig 2.1) – for Excel 2003 and earlier

Figure 2.1

For Excel 2007 click the Developer tab in the ribbon to see the Visual Basic button in
the Code group. (see Figure 2.1a)

Figure 2.1a

12
b) In the Record Macro dialog box, type "SetBackgroundColor" in the Macro Name
textbox to set the macro name. Leave all other option by default then click the Ok
button. This will start the macro recording. (see Fig 2.2)

Figure 2.2

c) In the Background Color Panel, select the Light Yellow color box. This action will
set the background of the current selected Range in light yellow color.

Figure 2.3

d) To stop the macro recording, click the Stop button (the navy blue rectangle) on the
Macro Recorder toolbar.

Figure 2.4

You have recorded a macro that set cell background to light yellow.
Now the recorded macro is ready for use. Before we run the macro, let's look into the
syntax.

* Press [Alt] and [F11] at the same time to load the Visual Basic Editor. The Visual
Basic Editor comes up.

13
* Expand the Modules folder in the Project Explorer by clicking on the plus (+) sign.
* Double click the Module1 folder to see the sub routine (macro). (Fig 2.5)

(Remember? You learn to do this in Lesson 1)

Figure 2.5

As the figure shows, the name of the sub routine is "SetBackgroundColor". The color
index for the light yellow is 36. The background pattern is solid.

(Note: The characters in Green with apostrophe in front are just comments and will
be ignored by VBA. You can always insert comments in your code by doing so.)

2) Run the Recorded Macro

We can run the macro within the Visual Basic Editor. This time we will run the
recorded macro in the worksheet.

a) On any worksheet, select a range. (Fig 2.6)

Figure 2.6

b) Run the recorded macro by select Tools...Macro...Macros... or press [Alt] and [F8]
at the same time. (Fig 2.7)

14
Figure 2.7

c) The Macro dialog box displayed (Fig 2.8). Since there is only one macro in the
module, by default the only macro, SetBackgroundColor is selected. Click the Run
button to run the macro.

Figure 2.8

d) Cells will now have light yellow background color.

Figure 2.9

e) You can edit the macro. In this example we change the :ColorIndex = 3. When we
run the macro, range selected will now have red background color.

f) We can add a macro to a toolbar as well. (i) we create a command button by


selecting View – Toolbars – Control Toolbox . Figure 2.10 display the control
Toolbox. Select the Command Button and embed it on the worksheet. (ii) After that
right click on the button and and edit. Type Click Me. (Fig 2.11)

15
Figure 2.10

Figure 2.11

g) Right click on the command button and select view Code and this will bring up the
VBE. In the Code window, type Module1.SetBackgroundColor

16
Figure 2.12

h) Go back to the worksheet and click on exit design mode (the highlighted icon
shown in Fig 2.13). This will add the macro to the commandbutton. When you click on
the button, it will run the macro “Module1.SetBackgroundColor”

Figure 2.13

You can use the macro execute a repetitive by adding a line of code as
…ActiveCell.Offset(1,0).Select… shown below.

17
Figure 2.14

When you click on the button, it will go down a row and set the cell color to light
yellow.

3) Summary

This is how you record a macro, assign a macro to a command button and execute a
repetitive task.

18
Lesson 3 : Excel Collection Objects And Objects

In this Lesson, you will learn about:

Objects

VBA Collection Objects

The Application Object

Workbook and Window Objects

The Worksheet Object

The Range Object

1) What is object?

It really is a pretty simple thing to understand. You can think of objects as separate
computer programs with specific (and often common) functions that are available for
repeated use in your programs.

Objects are dynamic in that they can be easily manipulated in code with the various
parameters used to define them.

For example, consider a car. A car can be described by its size, color, and brand
(among other things). For example, it might be a SUV, sports car, convertible and etc.
The color, size, and brand are all adjectives that describe the car. Thus, they are all
properties of the car.

A car can also perform various actions like move straight or turn. Moving and turning
are action verbs that tell you what tasks the car can do. Moving and turning are
methods of the car. Finally, the car is built out of other objects such as a frame,
wheels, steering, and tyres.

These objects, in turn, have their own properties and methods. For example, a car
wheel is of a certain diameter, is built out of aluminium or titanium alloys, and it turns
or rolls. The diameter and type of material are properties of the wheel object, and to
turn or roll would be two of its methods. So you see, there is sort of a hierarchy to the
objects in your car and the car object itself sits at the top of the hierarchy.

I could take it further. For example, a wheel is built from a tyre, rim, and spoke
objects. The tyres are built from organic polymers, and so on, and so on. The
description continues until eventually you will get to the objects at the very bottom of
the hierarchy.

In Excel, I bet that you’re already familiar with many of its objects. For example,
there are Workbook objects, Worksheet objects, Range objects, Chart objects, and
many more. These objects are the building blocks to construct a program with VBA.

19
The rest of this Part C, I will show you how to use a few of Excel’s objects, and in
particular, some of its top-level objects.

a) VBA Collection Objects

To understand what is collection objects in VBA, just think of a collection of cars.


The car objects in your car collection can be different sizes, colors, and brand, but
they are all cars. So, VBA collection objects means that it is a group or collection of
the same object types.

For example, any Workbook object belongs to a Workbooks collection object. The
Workbooks collection object contains all open Workbook objects. The Excel window
shown in Figure 3.1 contains three open Workbook objects (Book1, Book2, and
Book3). Collection objects enable you to work with objects as a group rather than just
working with a single object.

Figure 3.1

The hierarchy of Excel Objects

Figure 3.2

20
There are too many objects in Excel to cover them all. So in this Part, I’ll only explain
to you the objects shown in the Figure above. My goal is to get you comfortable
navigating through the object model and learning how to use the objects on your own.

b) The Application Object

At the top of the hierarchy is Application object. It represents the entirety of the Excel
application. As the top-level object it is unique and thus, seldom needs to be
addressed in code.

However, there are a few occasions when you must use the Application object’s
qualifier in code.

For example, the Width and Height properties used to set the size of the application
window must be reference explicitly in the VBA code. Other example will be the
DisplayFormulaBar property used to show or hide the formula bar.

Application.Width = 800

Application.Height = 550

Application.DisplayFormulaBar = False

You need to use the Application object qualifier, most of the time, to set properties
pertaining to the appearance of the Excel window, such as shown above, or the overall
behaviour of Excel as shown below.

Application.Calculation = xlManual

Application.EditDirectlyInCell = False

Application.DefaultFilePath = “D:\My Documents”

You need to use the Application object qualifier with the very helpful ScreenUpdating
property.

Application.ScreenUpdating = False

Another one will be the WorksheetFunction property.

Range(“C3”) = Application.WorksheetFunction.Sum(Range(“B1:B10”))

However if you just need to set properties of lower-level objects, then the Application
object qualifier is not needed.

ActiveCell.Formula = “=SUM(B1:B10)”

21
c) The Workbook and Window Objects

You may be unfamiliar with the Window object. Window objects refer to instances of
windows within either the same workbook, or the application. Within the Excel
application, the Windows collection object contains all Window objects currently
opened; this includes all Workbook objects and copies of any Workbook objects. The
Window objects are indexed according to their layering. For example, in Figure 3.1,
you could retrieve Book2 with the following code:

Application.Windows(2).Activate

because Book2 is the center window in a total of three Window objects. After Book2
is retrieved and thus brought to the top layer its index would change to 1 when using
the Windows collection object. This is different from accessing Book2 using the
Workbooks collection object.

Let’s take a closer look at the Workbooks collection Object via an example. There are
only a few properties and methods of the Workbooks collection object and their
functions are straightforward. Add the following procedure to a standard module in a
workbook.

Public Sub exampleWorkbooks()

Dim j As Integer

For j = 1 To 3

Workbooks.Add ‘add a new workbook

Next j

Workbooks(Workbooks.Count).Activate ‘activate book3

End Sub

In you execute this procedure by selecting example Workbooks from the Macro menu
in Excel, you will immediately see three new workbooks opened in Excel. After that it
will activate Book3

They are relatively straightforward to use, and you have already seen a couple of them
(the Add() method, Count property and the Activate() method). You may find the
Open() and Close() methods and Item property useful as well. Some of these members
will be addressed later, albeit with different objects. You will find that many of the
collection objects share the same properties and methods. This is not unusual, but be
aware that depending on the object you use, the parameters that are either available or
required for these members may vary.

Consider the following VBA procedure illustrating the use of the Close() method of
the Workbook object. The code can be placed in a standard or object module.

22
Public Sub CloseWorkbooks()

Workbooks(Workbooks.Count).Close SaveChanges:=False

Workbooks(1).Close SaveChanges:=False

End Sub

This procedure will close the first and last workbooks opened in Excel without
prompting the user to save changes.

In the example above, the Close() method of the Workbook object is used, not the
Close() method of the Workbooks collection object. If you want to close all
workbooks simultaneously, then use the Close() method of the Workbooks collection
object.

The code below will close the Workbooks collection object.

Workbooks.Close

In this case, there are no optional arguments allowed, so the user will be prompted to
save the currently selected workbook.

d) The Worksheet Object

The Worksheet object falls just under the Workbook object in Excel’s object
hierarchy. To investigate some of the events of the Worksheet object, the following
code has been added to the SelectionChange() event procedure of Sheet1 in a
workbook. (Figure 3.3)

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim msgOut As String

msgOut = “The name of this worksheet is “ & Worksheets(1).name

MsgBox (msgOut)

Worksheets(2).Select

End Sub

23
Figure 3.3

The SelectionChange() event procedure was is found in the object module of a


worksheet. The SelectionChange() event procedure is triggered whenever the user
changes the current selection in the worksheet. The Target argument passed to the
SelectionChange() event procedure is a range that represents the cells selected by the
user. I will discuss the Range object shortly; for right now, ignore it because the
current example does not use the passed argument.

The code in the SelectionChange() event procedure is straightforward. First, a string


variable is created and assigned a value (“The name of this worksheet is”) that is then
concatenated with the name of the worksheet obtained from the Name property of the
Worksheet object. The full object path is not used to return the name of the
worksheet, as this code will only be executed when the user changes the selection in
the first worksheet of the Worksheets collection object (Sheet1). Therefore, the object
path travels through the current Workbook object.

This is why index numbers can be used with the Worksheets property of the
Workbook object without having to worry about returning the wrong sheet. After
displaying the concatenated string in a message box, the Select() method of the
Worksheet object is used to select the second worksheet in the Worksheets collection
object.

Next, code is added to the Worksheet_Activate() event procedure of Sheet2. The


Worksheet Activate() event procedure is triggered when a worksheet is first selected
by the user or, in this case, by selecting the worksheet using program code
(Worksheets(2).Select). The code is essentially the same as the previous example.

Private Sub Worksheet_Activate()

Dim msgOutput As String

24
msgOutput = “This worksheet is “ & Worksheets(2).Name

MsgBox (msgOutput)

End Sub

The Worksheet_Activate() event procedure is not triggered when a workbook is first


opened, so it is not a good place for initialization routines intended to run as soon as a
workbook is opened. These procedures should be placed in the Workbook_Open()
event procedure.

The Sheets collection object is nearly identical to the Worksheets collection object
and the two objects can often be used interchangeably (as is the case in the previous
two examples). The difference between these two objects is that the Sheets collection
object will also contain any chart sheets open in the active workbook. So, if you
expect chart sheets to be open in the workbook of interest, you should access
worksheets using the Sheets collection object; otherwise, either collection object will
suffice.

i) Methods and Properties of the Worksheet

Select a sheet in the VBA Project window (Figure 3.3) and you can see 11 properties
of the worksheet in the Properties window of the VBE, properties for which you can
set a default value to begin with and that you can modify through the VBA procedure
whenever you wish.

There are 3 properties of a worksheet that you will use frequently:

· the name (name within parentheses),

· the name (without parentheses) like the caption appearing on the sheet's tab in Excel

· the visible property

To change the caption you can either do it in the property window of the VBE or in
Excel by right clicking on the tab then selecting "Rename". Programmatically you can
change the caption of a sheet with the following code:

Worksheets("Sheet1").Name= "Good"

The "Visible" property can take 3 different values. The first two are True or False
meaning the a certain sheet is or is nor visible that it is either hidden or not.

Worksheets("Good ").Visible= True


Worksheets("Good 1").Visible= False

Remember that formulas in cells are calculated even if the sheet is hidden but before
you can do anything programmatically on the sheet you must unhide it:

25
Worksheets("Good ").Visible = True
Worksheets("Good "). Select

Range(“A1”).Value = 10

The third value that the property "Visible" can take is very interesting. A sheet can be
very hidden " Worksheets("Good ").Visible = xlVeryHidden". In this state not only
the sheet is hidden but you can't see its name when in Excel you go to
"Format/Sheets/Unhide". The value xlVeryHidden can only be changed
programmatically. That means that only users that have access to the VBA code can
unhide this sheet. If your code is protected by a password only users with the
password can access the code and modify the "xlVeryHidden" value. You can use this
value of the property "Visible" to hide confidential information like credit card details
and personal info or to hide parameters that you don't want modified by the user.

Worksheets("Good ").Visible = True


Worksheets("Good "). Select

Range(“A1”).Value = 10

And hide it again…

Worksheets("Good ").Visible = xlVeryHidden

Remember also that formulas on other sheets referring to cells of a hidden or very
hidden sheet work even if the sheet is hidden or very hidden.

You might want to delete sheets. Here is the code to do so:

Worksheets("Good ").Delete

You might also want to add one sheet. If you use the following code VBA will add a
new sheet before the active worksheet.

WorkSheets.Add

If you want to be more precise as to the where and the how many you will use either
of the following procedures:

Inserting one sheet after the sheet which caption is "Good" the code is like this

Sub exercise2()
Sheets.Add before:=Sheets("Good")
End Sub

Inserting three sheets after the sheet which caption is "Good":

Sub exercise2()

26
Sheets.Add after:=Sheets("Good "), Count:=3
End Sub

Inserting one sheet at the beginning of the workbook. Notice the absence of double
quotes when using the rank of the sheet:

Sub exercise2 ()
Sheets.Add after:=Sheets(1)
End Sub

And if you want to add a new sheet at the end of the workbook you need to count the
sheets with Sheets.Count and use this value as the rank of the sheet after which you
want to add the new sheet:

Sub exercise2 ()
Sheets.Add After:=Sheets(Sheets.Count)
End Sub

e) The Range Object

You can use the Range object represents a group of one or more contiguous cells in an
Excel worksheet. It is extremely useful, as it allows us to manipulate the properties of
an individual cell or collection of cells in a worksheet. You will probably find
yourself using the Range object in every program you write using VBA for the Excel
application.

Consider the following code examples that use properties of the Range object.

Range(“B1”).Value=”Column B”

Range(“B1:G1”).Columns.AutoFit

Range(“B1:C1”, “E1:F1”).Font.Bold = True

The Range object is one example of a VBA collection object that does not use the
plural form of an existing object for its name. The Range object is a collection object
in the sense that it represents a collection of cells in a worksheet, even if the collection
represents only one cell.

First, note that a long object path is omitted from the examples above; thus, these
lines of code will operate on the currently selected worksheet. The first line inserts the
text Column A into cell B1 by setting its Value property. The Range property was
used to return a Range object representing a single cell (B1) in this example. You
have already seen several examples of the Value property previously. Although the
Value property exists for several objects, it is the Range object for which it is most
commonly used.

When you use the AutoFit() method of the Range object to adjust the width of
columns B through G such that the contents of row 1 will just fit into their

27
corresponding cells without overlapping into adjacent columns. This is equivalent to
the user selecting Format, Column, AutoFit Selection from the Excel application
menu.

The third and last example demonstrates setting the Bold property of the Font object
to true for two distinct ranges in the active worksheet. The two ranges are B1:C1 and
E1:F1. You are only allowed to return a maximum of two ranges, so adding a third
range to the arguments in the parentheses would generate a run-time error.

The examples above demonstrate just a couple of formatting methods and properties
belonging to the Range object (AutoFit(), Columns, and Font). If you are a regular
user of Excel, then you have probably surmised that there are numerous other
properties and methods related to formatting spreadsheet cells.

Recording a macro is a quick and easy way to generate the code you need without
having to search the documentation for descriptions of the desired objects, properties
and methods. After you have recorded the macro in a separate module, you can clean
up the recorded code and then cut and paste into your program as needed.

You may have noticed that the range arguments used in the examples above (B1,
B1:G1, etc.) are of the same form used with cell references in the Excel application.
This identical syntax is highly convenient because of its familiarity.

i) Using the Cells Property

The Excel Object Model does not contain a Cells object. In order to reference a
specific cells you use either the Cells property or the Range property. The Cells
property returns a Range object containing all (no indices used) or one (row and
column indices are specified) of the cells in the active worksheet. When returning all
of the cells in a worksheet, you should only use the Cells property with the
Application and Worksheet objects. For example,

Cells(2,2).Select

Here you’ve selected the cell B2 in the worksheet.

To return a single cell from a Worksheet object you must specify an index. The index
can be a single value beginning with the left uppermost cell in the worksheet (for
example, Cells(5) returns cell E1) or the index can contain a reference to the row and
column index (recommended) as shown below.

Cells(1, 4).Value=5

Cells(1, ”D”).Value =5

This is the familiar notation used throughout this book. Both lines of code will enter
the value 5 into cell D1 of the active worksheet. You can either use numerical or
string values for the column reference. You should note that the column reference
comes second in both examples and is separated from the row reference by a comma.

28
I recommend using the second example above, as there is no ambiguity in the cell
reference—though on occasion it’s convenient to use a numerical reference for the
column index. Now consider some examples using the Cells property of the Range
object.

Range(“C5:E7”).Cells(2, 2).Value = 100

Range(“C5:E7”).Cells(2, “A”).Value = 100

This code may confuse you because they appear to be trying to return two different
ranges within the same line of code; however, that is not the case, but you can use
these examples to more carefully illustrate how the Cells property works.

Before reading on, guess in what worksheet cell each of these lines places the value
100. If you guessed cells B2 and A2, respectively, you’re wrong. Instead, the value
100 is entered in cells D6 and A6, respectively, when using the above lines of code.
Why? It’s because the Cells property uses references relative to the selected range.
Without the reference to the Range object in each statement (Range(“C5:E7”)), the
current range is the entire worksheet, thus Cells(2,2) returns the range B2; however,
when the selected range is C5:E7, Cells(2,2) will return the second row from this
range (row 6) and the second column (column D). Using a string in the Cells property
to index the column forces the selection of that column regardless of the range
selected. The row index is still relative; therefore, the second example above returns
the range A6.

ii) Method and Properties Range (Cells, Rows and Columns)

Here is some code to move around and work with the Range object.

Selection and ActiveCell

The object Selection comprises what is selected. It can be a single cell, many cells, a
column, a row or many of these.

For example:

Range("A1:A50").Select
Selection.ClearContents

will remove the content (values or formulas) of the cells A1 to A50..

The ActiveCell is a very important concept that you will need to remember as you
start developing more complex procedures.

Range, Select

To select a cell you will write:


Range("B1").Select

29
To select a set of contiguous cells you will write:
Range("A1:A5").Select

To select a set of non contiguous cells you will write:


Range("C1,E5,F6").Select

Columns, Rows, Select, EntireRow, EntireColumn

To select a column you will write:


Columns("A").Select

To select a set of contiguous columns you will write:


Columns("A:B").Select

To select a set of non contiguous columns you will write:


Range("A:A,C:C,F:F").Select

To select a row you will write:


Rows("1").Select

You can also select the column or the row with this:
ActiveCell.EntireColumn.Select
ActiveCell.EntireRow.Select
Range("B1").EntireColumn.Select
Range("B1").EntireRow.Select

If more than one cell is selected the following code will select all rows and columns
covered by the selection:
Selection.EntireColumn.Select
Selection.EntireRow.Select

Cells, CurrentRegion

To select all cells then


Cells.Select

Offset

The commonly use Offset method allows you to move right, left, up and down.

For example if you want to move 2 cells to the right, you will write:
Activecell.Offset(0,2).Select

If you want to move 2 cells to the left,


Activecell.Offset(0,-2).Select

If you want to move two cells down:


Activecell.Offset(2,0).Select

If you want to move two cells up:

30
Activecell.Offset(-2,0).Select

If you want to select one cell and three more down:


Range(Activecell,Activecell.Offset(3,0)).Select
Range("A1",Range("A1").Offset(3,0)).Select

Column, Row, Columns, Rows, Count

For the following lines of code notice that you need to send the result into a variable.

myvar = Activecell.Column 'will return the column number

myvar = Activecell.Row 'will return the row number

myvar = Selection.Columns.Count 'will return the number of columns in the selection

myvar = Selection.Rows.Count will return the number of rows in the selection

myvar = Selection.CurrentRegion.Rows.Count 'will return the number of rows in the


current region of the selection

Value

When you want to enter a numerical value in a cell you will write:
Range("C1").Select
Selection.Value = 56

Note that you don't need to select a cell to enter a value in it, from anywhere on the
sheet you can write:
Range("C1").Value = 56

You can even change the value of cells on another sheet with:
Worksheets("Good").Range("C1").Value = 56

You can also enter the same value in many cells with:
Range("A1:B33").Value = 56

If you want to enter a text in a cell you need to use the double quotes like:
Range("C1").Value = "Nancy"

If you want to enter a text within double quotes in a cell you need to triple the double
quotes like:
Range("C1").Value = """Peter"""

Formula

To enter a formula in a cell you enter this code


Range("A1").Select
Selection.Formula = "=B8+C8"

31
Note the two equal signs (=) including the one within the double quotes like if you
were entering it manually. Again you don't need to select a cell to enter a formula in
it, from anywhere on the sheet you can write:

Range("A1").Formula = "=B8+C8"

If you write the following:


Range("A1:A8").Formula = "=C8+C9"

The formula in A1 will be =C8+C9, the formula in A2 will be =C9+C10 and so on. If
you want to have the exact formula =C8+C9 in all the cells, you need to write:

Range("A1:A8").Formula = "=$C$8+$C$9"

2) Simplifying object references

Application.Workbooks(“Book1.xls”).Worksheets(1).Range(“A1”).Value

You don’t need to fully qualify every object reference you make, like the above.
Excel provides you with some shortcuts that can improve the readability (and save
you some typing). For starters, the Application object is always assumed. Omitting
the Application object reference shortens the example from the previous section to

Workbooks(“Book1.xls”).Worksheets(1).Range(“A1”).Value

If Book1.xls is the active workbook, you can omit that reference too. This bring us
down to

Worksheets(1).Range(“A1”).Value

Further, if the first worksheet is the currently active worksheet, then Excel will
assume that reference and allow us to just type

Range(“A1”).Value

a) Working with Objects

You learn in numerous examples of objects on how to set their properties and invoke
their methods and events. There are a few more tools that can be very useful when
working with objects i.e. the With/End With code structure.

This code structure works well to simplify code; and the object data type, which
allows you to reference existing objects or even create new objects. We’ll look at an
example below.

The With/End With Structure

32
I always recommend the use of this structure because it makes your programs more
readable. Also you will often see the With/End With structure in recorded macros.
Consider the following code:

Range(“A1:D1”).Select

Range(“A1:D1”).Value = 100

With Selection.Font

.Bold = True

.Name = “Times New Roman”

.Size = 16

End With

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

End With

When executed, this code selects the range A1:D1 of the active worksheet using the
Select() method of the Range object.

In this case, the Selection property of the Window object is used to return a Range
object from which the Font property returns a Font object associated with the selected
range. The statement could have just as easily been written without the Select()
method and Selection property and entered using the Range property to return the
desired Range object (for example, With Range(“A1:D1”).Font).

Once inside the structure, any property of the object can be set without having to
qualify the object in each line of code. Subordinate objects and their properties can
also be accessed. Each line within the structure must begin with the dot operator
followed by the property or object name, then the method or assignment.

After all desired properties and/or methods have been invoked for the given object,
the structure closes with End With.

You will note that a second With/End With structure is used to set the horizontal and
vertical alignment of the selected range. This way your code looks clean and readable.

The With/End With structure is straightforward and particularly useful when a large
number of properties or methods of one object are to be addressed sequentially in a
program.

33
3) The Object Data Type

Lastly, the subject on Excel objects would not be complete without a discussion of the
object data type. If you find multiple instances of the same object in your program,
then you can use an object variable to handle the reference rather than constantly
retyping the qualifiers. Also, variables can be assigned meaningful names, making the
program easier to interpret. Object variable are similar to other VBA data types in that
they must be declared in code. For example,

Dim myObject as Object

declares an object variable named myObject; however, assigning a value to an object


variable differs from assignments to more common data types. The Set keyword must
be used to assign an object reference to a variable.

Set myObject = Range(“B1:C15”)

This will assign the Range object representing cells A1 through A15 to the variable
myObject. Properties of the object can then be initialized in the usual way.

myObject.Font.Bold = False

This sets the values in cells B1 through C15 to be displayed in bold-face type. Or,
using the Range object, the above example can be rewritten more efficiently as follow

Dim myRange as Excel.Range

Set myRange=Range(“B1:C15”)

myRange.Font.Bold = True

To be more efficient you can also include the library (Excel) in your declaration. Here
the Range object type will be referenced at compile time and VBA will have no
trouble working out references to the properties and methods of the object, as the type
of object and the library to which it belongs have been explicitly declared. You will
see more examples of object variable types in the as we go along.

4) Summary

When you do Excel programming, it’s all about manipulating the Excel objects. There
are so many things we can do with these object and you can be as creative as you
want. Like the neural network based forecasting addin develop by my company.

34
Lesson 4 : Variables And Data Types

In Lesson, we will learn…

Types of variable

Prompting for user input

Arrays

Interacting With Users

As Excel programming focuses on a spreadsheet application, it’s only natural that I


begin the subject of variables by asking you to think about the following: what types
of values can be entered into a spreadsheet cell and how you might use them? You
know that you can enter numbers and text in any spreadsheet cell in Excel.

Also, you may or may not know that the format of a spreadsheet cell can be changed
to one of several possibilities. For example, a number can be formatted such that the
value is Bold in style or red in color. It can also be formatted as currency or as a
percentage. Other than that text entered can be automatically converted to a date or
time. And etc...

1) Declaring Variables

Declaring a variable is to tell the computer to reserve space in memory for later use.
As a result your VBA code run much more efficiently. To declare a variable use a
Dim (short for Dimension) statement.

Dim myVar As Integer

The name of the variable is myVar. As you can see myVar begin with an alphabetic
character and cannot exceed 255 characters or contain any spaces. Do not use
punctuation marks or other unusual characters in the variable name, as many of them
are not allowed.

The use of underscore character is allowed and works well for separating multiple
words contained within a single variable name (for example, Car_Type).

Do not use VBA reserved keywords and don’t repeat variable names within the same
scope (discussed later in this Part). As a convention, the variable name should be
descriptive of the value it will hold. For example, if you use a variable to hold a type
of car, then a good name for that variable might be carType or CarType. My
preference is to begin a variable name with a lowercase letter and then capitalize the
first letter of any subsequent words appearing in the name. Try to keep the length to a
minimum so that it is more readable.

35
It is advisable to follow the naming conventions as they don’t contradict rules
established by VBA. To ensure that variables are always properly declared, use the
Option Explicit statement as the first statement in a module before you type any
procedure code. This is shown in Figure 4.1.

Figure 4.1

2) Variable Scope

A variable scope which can be declared as Private or Public variables, refers to the
time when a variable is visible or available to the program. When a variable is in its
scope, it can be accessed and/or manipulated. When a variable is out of scope, it is
unacessable—essentially invisible to the program.

A variable declared within the code block of a procedure (such as the Activate() event
procedure of the Worsheet), is a procedural level variable. Procedural level variables
are only available while program execution occurs within the procedure that the
variable was declared. In Figure 4.2, the variable myVar4 is only visible to the
program while the code in the Activate() event procedure of the worksheet executes.

36
Figure 4.2

What happen is that when program execute i.e. triggered by the Activate() event, the
variable myVar4 is dimensioned in memory. Program execution proceeds through the
event procedure until reaching the End Sub line of code, after which the variable is
released from memory and is no longer available. Each time the procedure executes,
the variable is created and destroyed. Thus, myVar4 will not retain its value between
calls to the procedure.

In this procedure the variable myVar4 will increment its value by one with each call
to the procedure.

The two variables are declared with the Dim, Private, and Public keywords (see
Figure 4.2). The Private and Public keywords are only allowed for variable
declaration in the general declarations section of a module. The variable myVar5 are
visible to any procedure within this module whereas myVar4 is only accessible from
the Worksheet Activate() procedure. Variables declared in the general declarations
section of a module (object or standard) with the Public keyword are commonly
referred to as global.

Therefore, the keywords Dim and Private have the same function in variable
declarations when used in the general declarations section of any module; the Public
keyword can be used to declare global variables in a standard or object module.

3) Data Types

When a data type is declared it means that you have defined the kind of value that

37
may be stored within the memory allocated for a variable. There are many data types;
the most common are shown in Table 4.1 below.

For example,

Dim myInt As Integer

Here, you intend for the variable (myInt) to contain only integer values.

a) Numerical Data Types

The numerical data types listed in Table 4.1 below are integer, long, single, and
double. If you declare a variable as an integer or long data type, it only can hold
whole numbers or non-fractional values within the specified ranges. It cannot hold
fractional or “floating point” values. For fractional or “floating point” values use a
single or double data type. Pay attention to the value of the number that you declare
within the variable. If the value gets too large for the data type, your program will
crash.

For example, the following code will generate an overflow error because the value
60000 is outside the allowed range for an integer data type:

Dim myInt As Integer

myInt = 60000

Figure 4.3

38
You need be careful when mixing numerical data types because you may not get the
desired result. The code below will execute without errors, but the variable answer
will hold the value 11 after execution, not 10.8 as you might want as the value stored
in answer is rounded to the nearest whole integer.

Dim answer As Integer

Dim num1 As Single

Dim num2 As Integer

num1 = 2.7

num2 = 4

answer = num1 * num2

To correct this error, change the variable answer to a single data type like below.

Dim answer As Single

Dim num1 As Single

Dim num2 As Integer

num1 = 2.7

num2 = 4

answer = num1 * num2

You can perform many types of mathematical calculations within your macros. You
can add, subtract, multiply, and divide variables; you can square and cube numerical
variables or raise them to any desired power. See Table 4.2 for a list of the operators
used for common mathematical operations in VBA.

i) Common Math Operators Used In VBA

Figure 4.4

You can be performed any mathematical operation on a numerical variable. The


following are a few examples:

Dim num1 As Integer

39
Dim num2 As Integer

Dim answer As Integer

num1 = 4

num2 = 2

answer = num1 + num2 ‘ answer Holds 6

answer = num1 - num2 ‘ answer Holds 2

answer = num1 * num2 ‘ answer Holds 8

answer = num1 / num2 ‘ answer Holds 2

answer = num1 ^ 2 ‘ answer Holds 16

answer = 2 ^ num2 ‘ answer Holds 4

I believe, you frequently encounter this type of mathematical calculation in source


code for all programming language.

b) String Data Types

To hold characters as text, the variables are declared as string data types . A string
data type can hold can be numbers, letters, or special symbols (for example,
punctuation marks). Basically, just about anything you can type on your keyboard can
be held within a string variable. To do this, use the String keyword like the example
below.

Dim myName As String

myName = “Peter Anderson”

There are two types of string variables, variable length and fixed length. The example
above is that of a variable length string because myText can hold just about any
length of text (see Table above). Following is an example of a declaration for a fixed
length string:

You can declare a string variable to hold a fixed length as well like the code below.

Dim myString As String * 10

myString = “ABCDEFGHIJKL”

Here, the string variable myString can hold a maximum of ten characters.

40
When you run the code, only the first ten characters in this example will be stored in
the variable i.e. “ABCDEFGHIJ”. Fixed length strings are often used as a part of a
user-defined data type. In most cases, it is advisable that you use the variable length
type as you will not know the length of the string to be stored in a variable.

When declaring a fixed-length string, do not use a comma in the number that specifies
the string size. In fact, never use commas when entering a numeric value in VBA.

c) Dates As Data Types

What do you do if you need to calculate the numbers of days between two dates?
Well. You declare the variables as date data type. If you declare a string variable to
store dates, you are unable to do the calculation.

Dim Today as Date

Dim LastTime As Date = # 6/6/2007# ‘here the variable is a fix date

Dim NumDay As Integer

Today = Now

NumDay = Today – LastTime

When you run the code, NumDay will stored the numbers of days that have elapsed
since he 6/6/07. Thus, the date data type gives your routines greater flexibility.

In VBA, place dates and times between two hash marks, as shown in the above
examples.

Date variables display dates according to your system’s short date format, and display
times according to your system’s time format (either 12- or 24-hour) so it depends on
the settings for the system on which the application is running.

d) Variant Data Types

Variant data types are comparable to the General category in the number format of a
spreadsheet cell in the Excel application. They are declared like this,

Dim myUnknown

Dim myUnknown2 As Variant

You can use Variant type variables to hold any type of data except a fixed length
string. This way Variant data types give the programmer more flexibility; but if
overused, they can be dangerous and slow down program execution. It is not
advisable to use them due to reason given above. For example,

41
Dim myVar As Integer

myVar = 5

myVar = “Five”

The will create a type mismatch error because an attempt is made to enter the string
“Five” into an integer variable. To solve this problem, you change the variable myVar
to a variant, the code will execute and myVar will hold the string value “Five” when
all is complete. The following code will run without error.

Dim myVar

myVar = 5

myVar = “Five”

These code enable the variable myVar to hold the integer value 5 (albeit briefly)
before being assigned the string value “Five”.

With the example code above, a potential problem exist and will crash the program.

If the variable is wrongly initialized to store “Five” instead of the numerical value 5, a
mathematical operation cannot be done and will taint the result of your program or
even worst the program will crash.

Using the variant data type will also make your program difficult to debug. Although
it may be tempting to use variants as a way to prevent errors that crash your program
(like the example above), in actuality the use of variants make your code “loose,” and
may cause logic errors that are difficult to find.

e) Boolean Data Type

The Boolean data type is simple. It holds the value true or false. It can also be
represented true as a 1 and false as a 0. You usually use it when dealing with
programming structures that use conditions. (I will explain this in another Lesson).
Declare and initialize a Boolean variable as follows:

Dim condition As Boolean

condition = False

f) Constants Data Type

You may sometime have variables that do not change its value when you execute
procedures. In which case it is good practice to declare it as a constant. It makes the
code easier to read and it is easier to change its value later if needed. Compare this
like using named ranges in your spreadsheet formulas.

42
Const PI As Double = 3.14159

Dim circumference As Single

Dim diameter As Single

diameter = 9.33

circumference = PI* diameter

4) Arrays

An array is a collection of variables that have a common name. For example, we refer
a specific variable in the array by using the array name and an index number.

For example, you may define an array of 7 string variables to hold the number of days
in a week. If you name the array NumDays, you can refer to the first element of the
array as NumDays(1), the second element as NumDays(2), and so on.

a) Declaring arrays

Before you can use an array, you must declare it like a variable in VBA with a Dim or
a Public statement. By default, VBA takes 0 as the lower index. You need to specify
the number of elements in the array by specifying the first index number and the last
index number. The following example shows how to declare the number of days in a
week.

Dim NumDays(1 to 7) As Integer

When you declare an array, you can choose to specify only the upper index.

As VBA assumes that 0 is the lower index, the following code both declare the same
100 element array:

Dim MyArray(0 to 99) As Integer

Dim MyArray(99) As Integer

If you want VBA to assume that 1 is the lower index for your arrays, your need to add
the following code in the Declarations section of your module:

Option Base 1

We assume the the lower index is 1 from now. The array code above, will now
represent a 99 element array

43
b) Assigning values to elements in an array

Suppose we have an one-dimensional array called MyArray and we wish to assign the
value 5 to the 3rd index slot, use the following

MyArray(3) = 5

c) Multidimensional arrays

We have look at one-dimensional arrays. Incredibly, VBA allow you to have as many
as 60 dimensions. The following example declares a 50-integer array with two
dimensions:

Dim MyArray(1 to 5, 1 to 5) As Integer

You can think of this array as occupying a 5-x-5 matrix. If we want to assign the
value 5 to the entry in the 2nd row and 5th column of the array, use

MyArray(2, 5) = 5

In other word, the integer value 5 is stored in (row 2, column 5) of the matrix
MyArray

For a three-dimensional array, think of it as a cube. Visualizing an array of more than


three dimensions is more difficult. Well you don’t worry about the fourth dimension
and beyond as I bet you’ll never use it.

d) Dynamic arrays

So far, we have been declaring arrays with a fixed number of elements. If you wish to
declare an array without specifying its size, use

Dim MyArray() As Integer

This is how to create dynamic arrays. Notice a dynamic array has a blank set of
parentheses:

To resize the array, you must use the ReDim statement to tell VBA how many
elements the array has. Most of the time, the number of elements in the array is
determined while your code is running. The ReDim statement can be used any
number of times, to change the array’s size as often as you need.

For example if you need to resize MyArray to a 10 x 10 matrix then you

ReDim MyArray(10,10) As Integer

Now you have change the number of elements in a dynamic array. When you

44
redimension an array by using ReDim, you clear all the values currently stored in the
array elements.

I’ll discuss on arrays again in Lesson 6.

5) Simple Input and Output with VBA

You already know how to get input from the user through the use of the Value
property of a spreadsheet cell. Apart from that, you can also generate output for the
user through the spreadsheet. However there may be times when you want something
more dynamic and dramatic way to interact with the user than using a spreadsheet
cell. The most common method for gathering input from the user and sending output
back is the InputBox() and MsgBox() functions.

a) Collecting User Input with InputBox()

The InputBox() function can be used to prompt and sometime to force a response
from the user. What happened is that, it will sends to the screen a dialog box that must
be addressed by the user before program execution continues.

Figure 4.5 below shows the dialog box.

Figure 4.5

And the code is this,

Sub GetName()
Dim MyInput

MyInput = InputBox("Enter your name")

MsgBox ("Hello ") & MyInput

End Sub

The InputBox() function example above returns the data entered by the user as a
string if the OK button is clicked or the Enter key is pressed on the keyboard. If the
user clicks the Cancel button, then a zero-length string is returned (“”). The syntax
required for creating an InputBox()(parameters in brackets are optional). It is rare that

45
you will need to use [, xpos] [, ypos] or [, helpfile, context]. See Excel help for details
on these.

InputBox(prompt [,title] [,default] [,xpos] [,ypos] [,helpfile, context], type)

Typically, the prompt, title, and sometimes the default are used. However, it is the last
argument "Type" that allows us to specify the type of data we are going to collect.
These are as shown below;

Type:=0 A formula
Type:=1 A number
Type:=2 Text (a string)
Type:=4 A logical value (True or False)
Type:=8 A cell reference, as a Range object
Type:=16 An error value, such as #N/A
Type:=64 An array of values

To look at another InputBox example that return number

Sub GetAge()
Dim MyInput As Integer

MyInput = Application.InputBox(Prompt:="How old are you ? " , Title:="ENTER _

AGE: ", Type:=1)


MsgBox ("You’re ") & MyInput

End Sub

As a rule, the prompt and title must be strings and enclosed in double quotation
marks. The title parameter is displayed in the title bar of the dialog box. The default
parameter is displayed in the text box of the dialog box.

b) Output with MsgBox()

By using the MsgBox() function, a message box like the one shown in Figure 4.3,
outputs a message to the user or ask a question that require a yes / no answer.

This is also useful as a way to inform the user about some type of problem. The
syntax for the MsgBox() function is as follow…

MsgBox(prompt[, buttons] [, title] [, helpfile, context])

Figure 4.6

46
You can see that I have use a string for the prompt, a vbOKOnly button and also a
string title. The example below was used to generate the message box in Figure 4.3
above:

Msg = MsgBox(“How Are You”, vbOKOnly, “Message”)

The prompt must be a string or string variable and is used as the message you want
the user to read. The buttons parameter requires a numeric expression (either an
integer or constant) and tells VBA what buttons and/or icons are to be placed on the
message box.

If you do not specify a button constant, the MsgBox() function uses the default
vbOKOnly that displays only the OK button. For a complete list of button choices,
look at Figure 4.4).

You can choose to display an icon (warnings or information type), a help button, and
add some additional formatting with your choice of buttons.

Figure 4.7

The MsgBox() function returns an integer between 1 and 7 depending on the button
selected.

Obviously this is only useful when there is more than one button. The return value
should then be used to select a course of action in your program.

Don’t put too many message boxes in your program as it is extremely annoying and a
disturbance to have to answer a message box when it’s not really necessary.

6) Summary

On this Part, I've discussed some important basics of programming; including


variables, data types, and constants. We also look at programming modules in VBA
and their effect on the scope of a variable. Also, I show to you several functions used
to manipulate values of type string and date.

47
Lesson 5 : Sub, Event And Function Procedures

In This Lesson, you’ll learn

Create Sub, Event and Function procedures

Ways to execute these procedures

How to execute Function procedures

1) Comparison of Subs, Events and Functions procedures

Procedures are constructed with VBA code in the Visual Basic Editor. The three most
common types of procedures are Sub, Function and Event

* A Sub procedure is consist of VBA statements that performs an action (or actions)
with Excel. Program code are executed when they are called (by other part of the
program)

* An Event procedure is predefines by VBA in the sense that you cannot change the
name of the procedure, nor the object within Excel to which the procedure belongs,
nor the conditions under which the procedure is triggered. Program code are executed
when they are triggered by an event (like the Worksheet_Activate event)

* A Function procedure is a group of VBA statements that performs a calculation and


returns a single value. (You cannot create a Function using the macro recorder)

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.

2) Private, Public, and Procedure Scope

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.

48
When you declare a procedure…

Public - makes the procedure visible to all other procedures in all modules in the
project.

Private - that the procedure is visible only to other procedures within the same module

And, if the Private or Public is not specified, then the procedure is public by default.

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…

49
· 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

50
This code when executed will display the message box “Welcome”. It will execute
whenever there is calculation in Sheet1 i.e. the Calculate event is triggered.

I’ll show you another example with a Workbook_Open event.

i) Open a new workbook.

ii) Activate the VBE by pressing Alt-F11

iii) Double-click the ThisWorkbook item. (Figure 5.2)

The VBE displays an empty Code window for the ThisWorkbook object.

iv) In the Code window on the right, select Workbook from the Object (left)
dropdown list.

The VBE will automatically enters the beginning and ending statements for a Workbook_Open
procedure

v) Enter the following code:

Private Sub Workbook_Open()

Dim Msg As String

If Today(Now) = 2 Then

Msg = “Its Monday. Welcome back “

Msg = Msg & “to the real world!”

MsgBox Msg

End If

End Sub

Workbook_Open is executed automatically whenever the workbook is opened. It uses


VBA’s Today function to determine the day of the week. If it’s Monday (i.e. day 2), a
message box greets the user to back to work. If it’s not Monday, nothing happens.

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)

51
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

A procedure that utilizes the Rect() function can be written as follows:

Private Sub CalcRect()

Dim length As Double

Dim width As Double

Dim result As Double

length = Val(InputBox(“Enter the length.”, “Length”))

width = Val(InputBox(“Enter the width.”, “Width”))

result = Rect(length, width)

MsgBox (“The area is” & result)

End Sub

The code is really very simple. First it asks 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.

52
3) Naming Subs and Functions

There are rules to follow when you name procedures, i.e

* VBA does not differentiate between uppercase and lowercase letters.


* You can’t use any of the following characters in a name: #, $, %, &, @, ^, *, or !.
* Letters, numbers, and some punctuation characters are allowed, but the first
character must be a letter.
* Each name should be less than 255 characters. (Of course, you would never make a
procedure name this long.)
* No spaces or periods in the name.

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.

4) Executing Events procedures

Events procedures are automatically executed when the event is triggered. You have
already seen a few examples of event procedures; such as the Click() event procedure
of a Command Button control, and the Calculate() event procedure of a worksheet.

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 Lesson
8)

5) Executing Sub procedures

Next, I am going to explain to you on the methods or ways to execute these


procedures. Else a procedure is worthless unless you know how to run it.

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

53
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.

a) Executing the Sub procedure directly

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

54
b) Executing the procedure from the Macro dialog box

Most of the time, you execute Sub procedures from Excel, not from the VBE.

The steps below describe how to execute a macro by using Excel’s Macro dialog box.

i. Activate Excel.

Alt+F11 is the express route (of course you can skip this step if Excel is already
active).

ii. Choose Tools-Macro-Macros (or press Alt+F8).

Excel displays the dialog box shown below (Fig 5.4)

iii. Select the macro.

iv. Click Run (or double-click the macro’s name in the list box).

Figure 5.4

c) Executing a macro by using a shortcut key

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.

55
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.

d) Executing the procedure from a button or shape

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.

56
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.

e) Executing the procedure from another procedure

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 are not an exhaustive list. There are other ways to execute
a procedure, I hope I can explain to you in future.

6) Executing Function procedures

You can only execute Functions in two ways i.e.

* By calling the function from another Sub procedure or Function procedure


*
* By using the function in a worksheet formula

Try this simple function. Enter it into a VBA module:

Function SquareRoot(num)

SquareRoot = num ^ (1/2)

57
End Function

Although this function is very simple, that is it only calculates the square root of the
number passed to it as its argument. But it is a good starting point for us to understand
functions especially the important concept on how functions return the value that pass
to it.

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.

a) Calling the function from a Sub procedure

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.

What happened is this,

* We pass an argument of 16 to the SquareRoot function to be calculated


* Here the function returns a value (4) and assigned to the Ans variable.
* After that, the MsgBox function displays the Ans variable as 4

You can also simplify the procedure GetSub by omitting the Ans variable code

Sub GetSub()

MsgBox SquareRoot(16)

End Sub

b) Calling a function from a worksheet formula

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

58
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!

Figure 5.6

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).

59
Lesson 6 : Control Logic And Loops

Specifically, in this Lesson, I will discuss:

Conditional Logic

Conditional Statements

If/Then/Else and Select/Case Code Structures

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

<> 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.

60
1) Conditionals and Branching

Let’s begin to examine a simple yet very useful VBA code structure. You will use it
all the time in your program i.e. the If/Then/Else. This structure is known as both a
conditional and branching structure because it uses conditional statements to change
the flow or direction of program execution.

a) If / Then / Else

There are several ways to implement this code structure. The most basic uses just one
line of code.

If (condition) Then Code statement

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

61
‘Block of code statements

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 < userguess =" age)"> is the “not equal” operator

If (userGuess <> answer) Then

MsgBox (“Wrong! The answer is “ & answer)

Else

MsgBox (“You got it!”)

End If

End Sub

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.

62
The condition

If (userGuess <> age) Then

can also be written as

If (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.

Private Sub FindSmallest ()

Dim a as integer

Dim b as integer

Dim c as integer

Dim Result as integer

a=5

b=7

c=9

IF (a < result =" a" result =" c" result =" b" result =" c" thehour ="hour(time)" thehour
=" 9" thehour =" 11" thehour =" 12" thehour =" 17" thehour =" 9"> 100000

SalesGrade = “Excellent”

63
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 Harder!”.

Here is another example demonstrates the "select case" statement.

Private Sub FindDay()

d =Weekday(Date)

Select Case d

Case 1

MsgBox "Sleepy Sunday"

Case 2

MsgBox "Monday again!"

Case 3

MsgBox "Just Tuesday!"

Case 4

MsgBox "Wednesday!"

Case 5

MsgBox "Thursday..."

Case 6

MsgBox "Finally Friday!"

64
Case else

MsgBox "Super Saturday!!!!"

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

65
This routine loops 10 times and adds 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.

A For-Next example with a Step

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

66
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.

A For-Next example with an Exit For statement

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”))

For Row = 1 To Rows.Count

If Range(“B1”).Offset(Row - 1, 0).Value = MinVal

Then

Range(“B1”).Offset(Row - 1, 0).Activate

MsgBox “Min value is in Row “ & Row

Exit For

End If

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

67
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.

A nested For-Next example

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. (Fig 6.1 is the result)

This routine has loop 50 times i.e 10 x 5.

Sub FormatBold()

Dim Col As Single

Dim Row As Single

For Col = 1 To 5

For Row = 1 To 10

Cells(Row, Col).Font.Bold = True

Next Row

Next Col

End Sub

Figure 6.1

68
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.

69
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 loop 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 runs 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.

70
· Whereas in a Do-Until loop, the program continue to loop until the condition is true.

Here’s the Do-Until syntax:

Do [Until condition]

statements]

[Exit Do]

[statements]

Loop

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:

Sub LoopUntilNot Empty()

Do

ActiveCell.Value = ActiveCell.Value * 3

ActiveCell.Offset(1, 0).Select

Loop Until IsEmpty(ActiveCell.Value)

71
End Sub

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

c) For Each -Next loop (Looping through a Collection)

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-

Next structure. The syntax is

For Each element In collection

[statements]

[Exit For]

[statements]

Next [element]

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

For Each ws In ActiveWorkbook.Worksheets

r = Int(Rnd)

ws.Range(“A1”).Value = r

Next ws

72
End Sub

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 unchanged if it is negative.

Sub FormatBold()

Dim Cell As Range

For Each Cell In Range(“A1:E50”)

If Cell.Value => 0 Then

Cell.Font.Bold = True

End If

Next Cell

End Sub

You can also use the For Each-Next to loop through each chart on a worksheet.

Here’s how:

Sub FormatCharts()

Dim cht As ChartObject

For Each cht In Sheets(“Sheet1”).ChartObjects

cht.Chart.ChartType = xl3DColumn

Next cht

End Sub

This program will loop through each chart on Sheet1 and changes each chart to a line
chart.

73
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.

74
Lesson 7 : Debugging And Error-Handling Techniques

In This Lesson, 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

75
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.

I will discuss more on this error later.

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.

2) Trapping and handling errors

The primary goal of error handling is to write code that avoids displaying Excel’s
error messages as much as possible. You need to anticipate potential errors and deal
with them.

So, how do we handle and debug the errors. Let me show you a few methods.

a) Insert break points in a subroutine

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.

76
Figure 7.1

Figure 7.2

77
b) Step through a procedure

You can debug your procedure by stepping through the execution of the code one line
at a time. Unlike break points, you trace the codeline 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

Figure 7.4

78
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.

3) A further discussion on runtime errors

To get things started, I developed a short VBA macro. Activate the VBE, insert a
module, and enter the following code:

Sub ErrorExample_1()

Dim Num As Integer

‘ Prompt for a value

Num = InputBox(“Enter a value”)

‘ Insert the square root

ActiveCell.Value = Sqr(Num)

End Sub

Figure 7.4a

This procedure asks the user for a value. It then enters the square root of that value
into the active cell.

You have entered “1q” which is wrong. The message Run-Time ‘13’ will be display
(Fig 7.4b). 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 occurs,
the highlighted line of code shown in Figure 7.5.

79
Figure 7.4b

Figure 7.5

To improve the procedure, you have to anticipate this error and handle it more
gracefully.

Here’s a modified version of ErrorExample_1()

Sub ErrorExample_1()

Dim Num As Integer

‘ Prompt for a value

Num = InputBox(“Enter a value”)

‘ Make sure the number is nonnegative

If Num <>

MsgBox “You must enter a positive number.”

80
Exit Sub

End If

‘ Insert the square root

ActiveCell.Value = Sqr(Num)

End Sub

I use an If-Then structure checks the value contained in the Num variable. If the user
enters a value other than an integer, the procedure displays a message box containing
information that you can actually understand. The procedure ends with the Exit Sub
statement, so the error never has a chance to occur.

4) Using the On Error statement

a) On Error Resume Next

The procedure below will demonstrate how this On Error Resume Next works. 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

81
Figure 7.6

When you run the procedure it will produce…

Figure 7.6a

As you can see in Figure 7.6, the value in Range(“A3”) is not an integer but the
procedure continues 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 occurs 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 ensures 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 occurred. 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

b) 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.

Let’s look at an example. Modify the example above to this code:

82
Sub ErrorExample_3()

On Error GoTo errorHandler

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)

Exit Sub

errorHandler:

MsgBox ("VBA skip the line of code containing a runtime error")

Resume Next

End Sub

In this example, the program jump to the errorHandler part of the code (see Figure
7.7) as error occurs and display the message box in Figure 7.8. Click the Ok button
and the procedure will finish executing the code. Note: don’t forget to put a colon
after the errorHandler label.

83
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.

Enter the code below in a module:

Sub ErrorExample_4()

On Error GoTo errorHandler

Dim total As Integer

84
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)

Exit Sub

errorHandler:

Select Case Err.Number

Case 13

MsgBox ("Make sure an integer is entered")

Case Else

Resume Next

End Select

End Sub

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 Fig 7.9a below;

85
Figure 7.9a

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.

Generally, you can use the On Error statement in three ways, (Fig 7.9b)

Figure 7.9b

Sometimes its alright to ignore errors. In fact we treat them as “friendly error”. In the
example below, we need to divide the value in the Range(“A1:A6”) with another
value

Sub ErrorExample_5()

On Error Resume Next

Dim totalSales As Integer

Dim branchSales As Single

86
Dim sales As Range

Set sales = Range("A1:A6")

totalSales = 100

For Each cell In sales

branchSales = totalSales / cell.Value

Next cell

End Sub

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 executed 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.

87
Lesson 8 : VBA UserForms and ActiveX Controls

In this Lesson, 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.

1) Adding a Form to a Project

88
To add a form to a project, activate the VBE and select Insert/UserForm from the
menu bar in the VBA IDE as shown in Figure 8.1 below…

(Figure 8 .1)

2) Components of the UserForm Object


Just like you select a Worsheet properties, when you select a form, its properties
appear in the Properties window in the VBA IDE (see Figure 8.1). Table 8.1 lists
some of the properties of the UserForm object that you will commonly set at Design
Time.

Selected Properties of the Userform Object

Property Description

Name Sets the name of the UserForm object for use as a code reference to
the object.
Caption Sets the text displayed in the title bar.

89
BackColor Sets the background color of the form.

Height Sets the height of the form.

StartUpPosition Sets the position of the form on the screen when displayed.

Width Sets the width of the form.

(Table 8.1)

Forms represent separate entities in a VBA project and have their own code window.
To view the code window (module) double click on the UserForm object, or hit F7
(all with the form selected). 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.

(Figure 8.2)

90
Generally, the behaviour of variables and procedures for User Form 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 Lesson 3 and 4. 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 User Form object has several event procedures, including Click (), Activate (),
and

Initialize () among others. To view the full list of event procedures of the User Form
object, select the User Form 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 User Form
object.

Event Description

Activate() Triggered when the User Form is activated

Initialize() Triggered when the User Form is loaded.

Click() Triggered when the User Form is click

Terminate() Triggered when the User Form is closed or unloaded.

(Table 8.2)

3) How to Add ActiveX Controls to a Form


Like the Worksheet object, the User Form object is a container object. It is used to
hold other objects. When a form is added to a project, the Control Toolbox should
automatically appear (see Figure 8.1). If the Control Toolbox does not appear, select
View/Toolbox from the menu bar.

You use the tools in the Control Toolbox to add controls to your User Form. 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

91
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 inserts 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 Command Button 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

92
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)

93
(Figure 8.4)

(Figure 8.5)

94
(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.

95
(Figure 8.7)

I suggest you use these naming convention for all the controls:

i) Label = lbl

ii) Textbox = txt

iii) Combobox = cbo

iv) ListBox = lb

v) CheckBox = chk

vi) OptionButton = opt

vii) RefEdit = rfe

viii) UserForm = frm

4) Showing and Hiding Forms


To load a form from the Excel application, use the Show() method of the UserForm
object in a procedure that can be triggered from Excel VBA.The basic syntax follows:

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.

96
Private Sub cmdDisplayForm_Click()

UserForm1.Show

End Sub

To hide a form from the user but retain programmatic control, use 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

5) Designing Custom Dialog Boxes Using Forms


We have discussed in Example A, the ActiveX controls Label, TextBox and
CommandButton to collect user input. As you can see, using the userform and the 3
controls has expand the capabilities of forms well beyond that of the InputBox() and
MsgBox() functions.

There are a few more ActiveX controls that I am going to show you below.

a) The Frame Control

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, behaviour.

97
(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.

c) The RefEdit Control

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.

98
Let’s look at an example to illustrate the combination of using the RefEdit control,
OptionButton, Label, Frame, CommandButton, TextBoxt controls.

Example B:

i. Insert a UserForm (see Figure 8.10)

(Figure 8.10)

ii. This dialog box has nine controls. Set the properties according to Table 8.4.

Controls Name Caption


Label lblResult Leave blank
TextBox 1 txtResult
OptionButton 1 optAverage Average
OptionButton 2 optMax Maximum
OptionButton 3 optMin Minimum
Frame 1 Calculate
RefEdit rfeInput
CommandButton 1 cmdCalculate Calculate
CommandButton 2 cmdClose Close

(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:

Private Sub cmdCalc_Click()

Dim myRange As Range

99
Set myRange = Range(rfeInput.Text)

If optAverage.Value = True Then

lblResult.Caption = "Average ="

txtResult.Value = Round(Application.Average(myRange), 2)

ElseIf optMax.Value = True Then

lblResult.Caption = "Maximum ="

txtResult.Value = Application.Max(myRange)

ElseIf optMin.Value = True Then

lblResult.Caption = "Minimum ="

txtResult.Value = Application.Min(myRange)

End If

End Sub

Double-click the Close button and enter the following Code…

Private Sub CloseButton_Click()

Unload UserForm3

End Sub

iii. Activate a Excel worksheet and name it “Example_C”

iv. Fill a Range on the Worksheet with random numbers

v. Go back to VBE and select UserForm3

Double click on UserForm3, select the Initialize and enter the following code:

Private Sub UserForm_Initialize()

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.

100
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)

Close the program by clicking the close button.

(Figure 8.11)

d) The List Box and Combo Box Controls

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.

101
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.
ColumnCount Sets the number of data columns to be displayed in the list.

ListStyle Indicates whether option buttons (single selection) or check boxes


(multi selection) should appear with 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.
List Run-time only. Used to access the items in the control.
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 behaviour 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.

102
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.

iii. Add the initialization code for the form:

Private Sub UserForm_Initialize()

With ListBox1

.AddItem "Boston"

.AddItem "Chicago"

.AddItem "Detroit"

.AddItem "Los Angeles"

.AddItem "Miami"

.AddItem "New york"

.AddItem "Omaha"

.AddItem "Pasadena"

.AddItem "San Diego"

.AddItem "San Francisco"

103
.AddItem "Denver"

.AddItem "Florida"

End With

' Select the first list item

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

Private Sub CommandButton1_Click()

Dim Msg As String

Msg = "You selected item # "

Msg = Msg & ListBox1.ListIndex

Msg = Msg & vbNewLine

Msg = Msg & ListBox1.Value

MsgBox Msg

End Sub

(Figure 8.13)

Note : the first item in a ListBox has a ListIndex of 0, not 1

104
Determining multiple selections

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.

To allow multiple selections in a ListBox, set the MultiSelect property to either 1 or 2.


You can do so at design time by using the Properties window or 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:

Private Sub CommandButton2_Click ()

Dim Msg As String

Dim i As Integer

UserForm2.ListBox1.MultiSelect = 2

Msg = “You selected” & vbNewLine

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

The message box below show the result.

105
To remove an item from the ListBox, you need to use the RemoveItem() statement.
Add a CommandButton3 and enter the code below.

Private Sub CommandButton3_Click()

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.

106
(Figure 8.14)

You usually 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:

If MultiPage1.SelectedItem.Caption = “Page 1” Then

MsgBox “Page 1 is active.”

107
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

The Scroll Bar Control

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 enables 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

108
(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

decrease when the user clicks on either scroll arrow.


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.

109
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.

6) Using Worksheet as the Container or Control Panel


As promised earlier, I’ll now show you how to use worksheet as a container or control
panel. Select a worksheet and activate the Control Toolbox by select View – Toolbars
- Control Toolbox on the Excel menu. Then just drag the control object from the
Control Toolbox into the worksheet. (You’ve done this on a UserForm…remember.

Example D: Controls use are Option Button, Frame, Label and TextBox. This time
we insert all these control on a worksheet.

i) Select a worksheet and rename it to Compounding

ii) Insert 5 text boxes, 4 option buttons and a command button.

iii) Format the worksheet shown in Figure 8.17

iv) Rename all controls properties according to Table 8.7.

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:

Private Sub cmdCalc_Click()

Dim Principal As Currency

Dim IntRate As Double

Dim IntEarned As Currency

Dim FutureValue As Currency

Dim RatePerPeriod As Double

Dim Periods As Integer

Dim CompoundType As Integer

Dim i As Double

110
Dim n As Integer

Principal = CCur(txtPrincipal.Text)

IntRate = CDbl(txtIntRate.Text) / 100

If optMonth.Value = True Then

CompoundType = 12

ElseIf optQuarter.Value = True Then

CompoundType = 4

ElseIf optSemi.Value = True Then

CompoundType = 2

Else

CompoundType = 1

End If

Periods = CInt(txtPeriods.Text)

i = IntRate / CompoundType

n = CompoundType * Periods

RatePerPeriod = IntRate / Periods

FutureValue = Principal * ((1 + i) ^ n)

IntEarned = FutureValue - Principal

txtIntEarned.Text = FormatCurrency(IntEarned)

txtAmtEarned.Text = FormatCurrency(FutureValue)

End Sub

Control Name Properties Caption


TextBox 1 txtPrincipal
TextBox 2 txtIntRate
TextBox 3 txtPeriods
TextBox 4 txtIntEarned

111
TextBox 5 txtAmtEarned
CommandButton 1 cmdCalc Calculate
OptionButton 1 optMonth
OptionButton 2 optQuarter
OptionButton 3 optSemi
OptionButton 4 optAnnual

(Table 8.7)

(Figure 8.17)

112
(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 applies 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)

(Download example file here)

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.

i) Select a worksheet, name it “Example E” and format it according to


Figure 8.19.

ii) Insert a ComboBox and SpinButton.

iii) On Range(“C15”) insert this function: =PMT(C7/C11,C9*C11,-C5)

iv) On Range(“C17”) insert this formula: =SUM(C15*(C9*C11))

v) On Range(“C20”) insert this formula: =C17-C5

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.

vii) Enter this code:

Private Sub Worksheet_Activate()

113
Me.ComboBox1.Clear

Me.ComboBox1.AddItem ("None")

Me.ComboBox1.AddItem ("Toyota Vios")

Me.ComboBox1.AddItem ("Honda City")

Me.ComboBox1.AddItem ("Toyota Camry")

Me.ComboBox1.AddItem ("Honda Accord")

End Sub

viii) Rightclick on SpinButton1 and select View Code.

Select the Change Event and enter this Code:

Range("C9").Value = Me.SpinButton1.Value

ix) Rightclick on SpinButton1 and select Properties

Enter the following:

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:

Private Sub ComboBox1_Change()

Dim loan As Single

Dim interest As Double

If Me.ComboBox1.Value = "Toyota Vios" Then

Range("C5").Value = 77000 'loan amount

Range("C7").Value = 0.045 'interest rate

ElseIf Me.ComboBox1.Value = "Honda City" Then

Range("C5").Value = 77500 'loan amount

Range("C7").Value = 0.055 'interest rate

114
ElseIf Me.ComboBox1.Value = "Toyota Camry" Then

Range("C5").Value = 150000 'loan amount

Range("C7").Value = 0.045 'interest rate

ElseIf Me.ComboBox1.Value = "Honda Accord" Then

Range("C5").Value = 145000 'loan amount

Range("C7").Value = 0.045 'interest rate

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.

115
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.

(Download example file here)

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.

116

You might also like