ProgrammingInExcelVBA AnIntroduction
ProgrammingInExcelVBA AnIntroduction
in
Microsoft Excel VBA
An
Introduction
Programming In Excel VBA by J.Latham
An Introduction Microsoft Excel MVP 2006-??
Table of Contents
OVERVIEW ..................................................................................................................................... IV
Why ........................................................................................................................................... iv
What .......................................................................................................................................... iv
Who ........................................................................................................................................... iv
How ........................................................................................................................................... iv
Anticipated User Skill Requirements ..................................................................................... iv
Copyright Acknowledgments................................................................................................... v
Creating this Guide ................................................................................................................... v
WHAT IS VBA?............................................................................................................................... 1
VBA: An Event Driven Language ........................................................................................... 1
VBA: An Object-Based Language........................................................................................... 1
THE EXCEL VBA IDE .................................................................................................................... 2
Getting to the VBA IDE ........................................................................................................... 3
To Be Explicit or Not ................................................................................................................ 4
TYPES OF CODE MODULES ............................................................................................................ 6
General Purpose Code Modules .............................................................................................. 6
Workbook Code Modules ........................................................................................................ 7
Workbook Events.................................................................................................................... 7
Worksheet Code Modules ........................................................................................................ 9
Worksheet Events ................................................................................................................... 9
The „Target‟ and „Cancel‟ Objects ......................................................................................... 9
Class and UserForm Modules ................................................................................................ 10
Class Modules ....................................................................................................................... 10
UserForms and their Modules ............................................................................................... 10
PROCEDURES: FUNCTION AND SUB.............................................................................................. 11
Functions.................................................................................................................................. 11
Subs .......................................................................................................................................... 12
Procedures: Public or Private ................................................................................................ 12
CONSTANTS, VARIABLES AND TYPING ........................................................................................ 13
Data Types ............................................................................................................................... 13
Our First Procedure ............................................................................................................... 15
Reserved Words ...................................................................................................................... 16
Comments and Remarks ........................................................................................................ 16
Error Handling: A Beginning ................................................................................................ 17
Constant and Variable Declarations Revisited .................................................................... 19
Procedure Level Scope ......................................................................................................... 19
Module Level Scope ............................................................................................................. 19
Public Scope.......................................................................................................................... 20
When to Use Constants and/or Variables ............................................................................. 20
GOOD PROGRAMMING PRACTICES.............................................................................................. 21
What is Good Code ................................................................................................................. 21
Good Programming Practice #2 ............................................................................................ 21
More Good Programming Practices ..................................................................................... 21
LOOPING STRUCTURES ................................................................................................................ 22
For … Next Loops ................................................................................................................... 22
Do... Loops ............................................................................................................................... 24
List of Figures
Figure 1 Excel VBA IDE - No Code Module Displayed................................................................ 2
Figure 2 Open the VBE from the Excel Tools Menu ..................................................................... 3
Figure 3 Excel VBA IDE Major Areas ........................................................................................... 3
Figure 4 The VBE [View] Menu Item Expanded ........................................................................... 4
Figure 5 Option Explicit in Effect .................................................................................................. 4
Figure 6 Setting Option Explicit Directive: Step 1 ......................................................................... 5
Figure 7 Setting Option Explicit Directive: Step 2 ......................................................................... 5
Figure 8 Insert a New General Purpose Code Module ................................................................... 6
Figure 9 VBAProject Showing the Modules Collection................................................................. 6
Figure 10 Working in the Workbook Code Module ....................................................................... 7
Figure 11 Viewing the Worksheet Event List................................................................................. 9
Figure 12 The VBE Debug Menu ................................................................................................. 16
Figure 13 MyFirstProcedure Results ............................................................................................ 16
Figure 14 BOOM! Unhandled Errors Are a Pain ........................................................................ 17
Figure 15 For...Next Loop Counting Results ................................................................................ 23
Figure 16 InputBox$() Example ................................................................................................... 33
Figure 17 InputBox$() Validation Failed Message ...................................................................... 33
Figure 18 Plain Vanilla MsgBox$() Displayed ............................................................................ 35
Figure 19 MsgBox Used to Obtain User Input ............................................................................. 35
Figure 20 Multi-Control UserForm .............................................................................................. 36
Figure 21 UserForm With Text Entry Boxes ................................................................................ 37
Overview
WHY
Why does this book exist? I wrote this book to hopefully provide a basic introduction to learning to
program using Visual Basic for Applications (VBA) as implemented in Microsoft™ Excel©. I have
attempted to provide a balance of basic programming concepts and good programming practices. Along
the way concepts are presented that often fall into the “advanced” category in other books. I don‟t believe
these concepts are “advanced” in that it takes more basic teaching to understand and use them, rather if
they are taught as part of that basic teaching they are no more difficult to learn than anything else in the
language.
The goal is not to make you all-knowing of all things VBA in Excel, but rather to try to give you a basis
for understanding what VBA for Excel is capable of, helping you put code samples you obtain from a
variety of sources to work for you, to learn how to modify and adapt recorded macros to make them more
generic and useful to you, and to encourage you to learn more about the language so that you can take full
advantage of the worlds #1 spreadsheet application.
WHAT
What is taught in this book? The basic elements of VBA coding are covered and hopefully taught in it.
The First Edition will pretty much just cover what I decide to cover. If anyone has specific things that
they feel would be beneficial to the budding VBA programmer, I will certainly entertain the idea of
including them in later revisions to it. You can send such suggestions via email to:
HelpFrom@JLathamsite.com
The difficulty in presenting this type of material is that teaching VBA coding requires knowledge of many
things that have inter-dependence on one another. This inter-dependence can be an actual physical
dependence, but more often it is a dependence based on the knowledge of many different elements of the
programming environment: the syntax or command structure for instructions; a knowledge of the
“objects” in the application and their attributes (properties) and the things you can do to or with them
(methods), along with many other things. By necessity some things must be taught before others in order
to build from a basic understanding to more complex understanding as the studies continue. In discussing
some of the basics, more advanced concepts may be used in the process and the reader must accept those
as-yet-unexplained concepts and pieces simply on faith or with an “it is what it is” attitude for a while.
Since this is an Introduction to VBA for Excel, many details of many subjects and areas are left to be
discovered by the student on their own through experience, further study and examples from other sources
in the future.
WHO
This book is for anyone desiring to learn how to extend the functionality and usefulness of Excel through
added capabilities often only available through VBA.
HOW
You will learn to begin programming in Excel VBA by reading through this book and you will use your
copy of Excel to „follow along‟ and create procedures and observe them at work.
ANTICIPATED USER SKILL REQUIREMENTS
This book is designed to be used by those with the Excel® knowledge typical of the „average‟ office user.
This means that the user is expected to be familiar with general Excel® features and functions such as the
use of menu and icon toolbars, selecting worksheets and cells, creating simple formulas in cells,
„navigating‟ within Excel®, and opening, saving and closing the Excel® application and Excel® created
workbooks (.xls files).
What is VBA?
Visual Basic for Applications (VBA) is an extensible programming language that is made up of a
core set of commands and extended on a per-application basis to be able to work directly with
objects in that application. This means that VBA for Excel knows about things like workbooks,
worksheets, cells and charts and more; while VBA for Access knows about tables, queries,
reports and data entry forms, among other things. The core can even be licensed for use by 3rd
party companies to permit it to be used with their application(s). This was the case with Visio
before Microsoft bought the product for use under their banner.
VBA can probably be best described as an object-based (but not a true object oriented) language
that is event driven. Let‟s look at the event driven side of it first.
VBA: AN EVENT DRIVEN LANGUAGE
Event driven means that nothing happens until something happens. Rather Zen-like isn‟t it? Ok,
once again, but with a better grasp of reality. In VBA, no code executes except in response to
some event taking place (or at the command of the code once it is started by some event). An
event can be any one of many things. Opening an Excel workbook creates, or triggers, the Open
event, closing it triggers the BeforeClose event. Selecting a worksheet in the workbook will
cause a Deactivate event to occur on the page that had been selected and an Activate event to
happen to the new sheet you select. Many events occur that don‟t have code associated with
them, and that‟s to be expected; something doesn‟t have to happen every time something else
happens. A shape (square, button, text box) actually triggers a Click event when it is clicked on
– you may or may not have code associated with one of those shapes to respond when it is
clicked on.
Event driven also means that you never know exactly when code for an event will be called upon
to run. For example, you may have a process that runs when a particular sheet is selected that
takes a long time to complete – perhaps checking for and hiding unused rows, or refreshing the
data on the sheet from another data source. While that is going on, you may click a button on the
sheet to try to do something else, such as sort the data on the sheet. Excel will, for the most part,
deal with the timing of when these processes are performed. You do need to be aware that it is
possible to request an operation to begin before another has completed. Most of the time this
does not cause any problem at all, but sometimes it can.
VBA: AN OBJECT-BASED LANGUAGE
Object based means that when referring to the components of the application, things like
workbooks, worksheets, cells, charts, etc. are „objects‟. An object has certain attributes. Just a a
person has attributes like height, weight, eye and hair color, the objects in Excel have attributes
(Properties) such as value, height, width, color and more. Additionally, objects can do things or
have things done to them – these actions are known as Methods. For example, a workbook can
be opened or closed; a cell can have its shading altered, a worksheet can be deleted.
While you may use constants and variables in your code that seemingly don‟t have any direct
relationship to an object, in the end the results of processing or calculations will probably be
used to alter some property of an object in the workbook: the value in a cell, the range of
information used as a data series on a chart, whether or not a particular sheet is visible or not at
any given moment. With all of this under our belt, we can now look at how to access this power.
This is the VBE [View] menu option expanded. As you can see,
it permits you to display any of the 5 major areas of the IDE and
even more that are useful in special circumstances such as the
Object Browser and the Locals and Watch windows.
Note: To close any of these windows once you‟ve opened them,
simply click the classic “close window” [X] in the upper right
corner of the window.
To create a new general purpose module you can use the [Insert] | Module
option from the VBE menu toolbar:
Just what are the workbook events? You can get a complete list of them from the code window
while the Workbook Code module content is displayed: You can display that content by double-
clicking the ThisWorkbook object in the VBAProject window. You‟ll get a display similar to
this
Just what are the worksheet events? You can get a complete list of them from the code window
while any Worksheet Code module content is displayed: You can display that content by
double-clicking any worksheet object in the VBAProject window. The code module for that
sheet will be displayed. You‟ll get a display similar to this
Often in worksheet event stubs provided by the VBE you will see reference to two special
objects (sometimes more or others also): Cancel and/or Target.
Target represents the Range [which is an object that represents a single cell, a group of cells, one
or more rows and/or one or more columns) that is active at the time the event took place. Think
of Target as the actual object itself. Anything you do to Target is done to the actual Range that
it represents. Changes made to Target will appear on the sheet itself.
The Cancel object is a Boolean type object. A Boolean object can only have one of two
conditions assigned to it: TRUE or FALSE. By default a Boolean object is FALSE (and has a
numeric value of zero). If your code sets Cancel = TRUE then the underlying event action is
cancelled: the DoubleClick never takes place or the RightClick never gets completed. These are
handy events to use to take very special actions with – you can have someone double-click in a
cell (and set Cancel = True) to begin a series of events unique to that cell. A real world example
of this type of thing in one application I developed is that in a data area matrix that has dates in
Quite frankly we‟re not going to cover Class Modules. That is an “advanced” topic in my
considered opinion, and 99.9% of all coding needs can be met without using them. Creating a
class takes much more preparation and thought than we have the time or space for in this book.
UserForms and their Modules
We will cover both UserForms and their underlying code modules separately later. Think of
them much as worksheets and worksheet modules. Each UserForm has its own code module that
contains the code associated with all objects on the UserForm.
Finally, you declare the type of value that the function will return (fType). The type can be any
valid type such as String, Boolean, Integer, Float, Double, Long, Variant, etc.
A Function ends with the End Function statement. Everything in between the function‟s
declaration and the End Function statement is part of the function itself.
Here is an example of a function that calculates and returns the square of a value passed to it:
Function SquareOfNumber(anyInteger as Integer) As Long
SquareOfNumber = anyInteger ^ 2
End Function
Here is how it might be called from another procedure:
Dim aNumber as Integer
Dim numberSquared as Long
aNumber = 15
numberSquared = SquareOfNumber(aNumber)
After all of that numberSquared will contain 225 (15 * 15, or 15^2)
The function could also be called from a worksheet in a cell like this:
=SquareOfNumber(15)
And 225 would appear in the cell. Actually, Excel would display the formula as:
Procedures: Sub and Function Page 11
Copyright © 2008 by J.L.Latham, All Rights Reserved.
Programming In Excel VBA by J.Latham
An Introduction Microsoft Excel MVP 2006-??
=squareofnumber(15)
Excel makes UDF names all lowercase to distinguish them from built-in worksheet functions.
SUBS
Sub procedures are just like Functions, except that they do not return a value in the same way
that a Function does. They can accept arguments, or not, just like a Function does.
A Sub starts with its declaration:
Sub subName (argument1 As Type, argument2 As Type)
Where Sub is a reserved word declaring the start of the definition of the procedure.
subName is the name you assign to the procedure.
Within the parenthesis you define the list of arguments and their types that are to be passed to the
Sub for it to use to get its job done. You do not have to pass any arguments, but you do have to
use the parenthesis, as:
Sub noArgumentProcess()
There is no declaration of the type of value that the sub will return because if there were, then it
would be a Function and not a Sub.
A Sub ends with the End Sub statement. Everything in between the sub‟s declaration and the
End Sub statement is part of the sub itself.
PROCEDURES: PUBLIC OR PRIVATE
By default all procedures are “Public”. That is to say that they can pretty much be used from
anywhere in the project. For Sub procedures, it also means that they show up in the Tools |
Macro | Macros list as available to be run through that interface and for Functions, public
functions can be used as UDFs. You can explicitly declare a procedure to be Public by
preceding its declaration with the word “Public” like:
Public Sub aPublicSub()
or
Public Function aPublicFunction(arg1 As Variant) As Variant
But sometimes we don‟t want the user to have access to a procedure, or don‟t want other
modules to be able to use a procedure in another module. For those times, you can make a
procedure only accessible from within the code module that it exists in by preceding its
declaration with the word Private. You‟ll notice that all of the Workbook and Worksheet built-in
event procedures are declared as Private. Subs that are declared as Private do not show up in the
Tools | Macro | Macros list, and private functions are not available for use as UDFs. Examples
of private declarations are:
Private Sub aPrivateSub()
or
Private Function aPrivateFunction(arg1 As Variant) As Variant
Private procedures are normally only usable by other procedures in the same module with them.
There is an exception to the rule; you can get around it by using Run “privateProcedureName”.
You can also use the Call command in a similar fashion. See the Excel VBA Help topic on
CALL for limitations in using it. When you use Run or Call the procedure is executed and
control returns to the line of code following the Run or Call statement.
Procedures: Sub and Function Page 12
Copyright © 2008 by J.L.Latham, All Rights Reserved.
Programming In Excel VBA by J.Latham
An Introduction Microsoft Excel MVP 2006-??
Decimal – this is a special type that almost doesn‟t exist. The quote from Excel Help tells this
tale: “…signed integers scaled by a variable power of 10. The power of 10 scaling factor
specifies the number of digits to the right of the decimal point, and ranges from 0 to 28. With a
scale of 0 (no decimal places), the largest possible value is +/-
79,228,162,514,264,337,593,543,950,335. With a 28 decimal places, the largest value is +/-
7.9228162514264337593543950335 and the smallest, non-zero value is +/-
0.0000000000000000000000000001.
Note At this time the Decimal data type can only be used within a Variant, that is, you cannot
declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is
Decimal using the CDec function.”
Now if you run the procedure again and enter a word or something other than a number, you are
gently requested to correct the error of your ways and allowed to try again without the entire
application crashing to the ground.
Now we will continue our interrupted discussion of declaring variables and constants.
A variable declared inside of a procedure has procedure level scope. The variables and constants
we declared in MyFirstProcedure had procedure level scope.
Procedure level variables are created when the procedure begins to execute, they are only
available to be used within the procedure and they cease to exist when the procedure ends at the
procedure‟s Exit Sub or Exit Function statement.
As with any good rule, this one has an exception. If you declare the variable using the Static
declaration instead of Const or Dim statements, then the variable will retain the last value
assigned to it when the procedure ended as its initial value the next time the procedure executes.
A trivial example: try placing this code in a module and just press [F5] several times to watch the
value of myStaticCounter go up each time.
Sub StaticsAtWork()
Static myStaticCounter As Integer
'each time this procedure is called, myStaticCounter value will increase by one
myStaticCounter = myStaticCounter + 1
MsgBox myStaticCounter
End Sub
Even though myStaticCounter retains its last value, it still cannot be accessed to determine its
value outside of the procedure – it retains its procedure level scope.
You cannot use the Public or the Private declarations within a procedure. For all practical
purposes all declarations within a procedure are private to that procedure.
Module Level Scope
The next step up the scope food chain is module level scope. These are constants and variables
that can be used/evaluated/modified (for variables) by any procedure in the module. Module
scope variables and constants are declared in the General Declarations Section of a module.
The General Declarations Section of a module is the area ahead of any declaration of a
procedure. The Option Explicit statement that we‟ve already seen is in this section of the
modules. Declare your module scope variables and constants after the Option Explicit statement
and before any procedure declaration.
You can use the Dim and Const statements to make declarations in this area but it is clearer to
the reader if you use the Private declaration statement so that readers will know later that these
variables and constants are private/local to the module:
Private anyModuleLevelScopeVariable As Variant
Private Const anyModuleLevelScopeConstant = “The whole module can see me!”
Public is a term that was previously Global. A variable or constant declared as Public in the
General Declarations section of any standard module has visibility/accessibility in any procedure
in any module in the entire project.
Why not just declare everything Public and be done with it? Because in more than the simplest
application you will invariably change the value of a public variable at the wrong time/place
causing yourself mega-headaches in debugging it all. Overall it is best to keep the scope of your
declared values at the lowest level possible. You will have fewer problems and easier debugging
all around by doing that.
I personally like to put all of my Public constants and variables into a single module with
comments provided to explain where they are used and what they are used for. This provides a
single central point of management for the Public values.
What are candidates for Public values? Look for things that you find yourself using repeatedly
for the same purpose in several areas of your project – perhaps using the same worksheet name
to perform operations with the sheet; definitions of the layout of those worksheets, constants that
your logic depends on heavily and are used in multiple areas.
When to Use Constants and/or Variables
One question that comes up from time to time is “why use constants at all – why not just use
their value(s)?”. I‟ll answer your question with a question: which is more informative to you
here?
If ActiveCell.Row < 4 Then
Or
If ActiveCell.Row < firstRowWithData Then
Not only is the second form more understandable, it keeps you from having to track down every
place you‟ve used 4 as a value and trying to figure out if you mean the first row with data on a
sheet, or are comparing ages of pre-school children, or seeing if the word Mississippi has the
correct number of 'i's in it.
Finally, using named variables/constants helps prevent typographic errors. [Debug] | Compile
VBAProject will find errors in variable/constant name spellings rapidly, but it cannot do
anything at all to determine that you typed a 4 when you really meant to type a 5 and just had
your finger on the wrong key when you typed it. A common error, known as FFS (fat finger
syndrome).
Looping Structures
One thing that computer code is good at doing is something dull and tedious for us human types:
repetitive actions. A macro in itself is a way of doing something repetitive, with varying levels
of complexity, over and over with ease and without boring ourselves to death doing it. Each
time we run a Macro or cause a procedure to be called, we are performing some repeated
process.
Within procedures we may also need to perform a particular task many times. The use of
looping structures such as:
For … Next
For Each … Next
Do … Loop
Do … Until
and
Do … While
All give us slightly different ways to perform actions, calculations and other processing many
times in a relatively small section of code.
FOR … NEXT LOOPS
The simplest and oldest loop structure in Basic is the For…Next loop. The general form, or
syntax, of the command is
For counter = startCount To endCount Step stepValue
Executable statements and comments to be performed
Next
For is a reserved word that marks the beginning of the loop.
counter is a variable that is used to control how many times the code within the loop is
performed.
startCount is a variable, constant, or calculated value that determines the initial value of counter.
To is a required reserved word that separates the starting value from the ending value
endCount is a variable, constant, or calculated value that determines the maximum value that
counter may be assigned before the loop terminates.
Step (and stepValue) are optional arguments that allow you to change the way counter values
between startCount and endCount are calculated. stepValue may be a variable, constant, or
calculated value. The default, when Step stepValue are omitted from the command, is 1 (one).
Next is a reserved word that is used to mark the end of the For loop.
For x = 0 To 0
MsgBox "inside of the loop"
Next
End Sub
You will see the message once, proving that the code inside of the loop did run.
If a For...Next loop runs to completion, the value of the counter value will be one more than the
endCount. Example:
Sub test()
Dim x As Integer
Dim y As Integer
For x = 1 To 10
y=y+1
Next
MsgBox "Counter x is: " & x & vbCrLf & "Value y is: " & y
End Sub
The message displayed should be:
Note: in the MsgBox statement, vbCrLf is a built-in VBA constant that provides a newline; that
is, it provides a Carriage Return and a Line Feed, thus they called it vbCrLf.
Use [Ctrl]+[End] to break into that code if you actually try running it.
There is nothing in that code to stop the loop from processing, so it pretty much runs forever.
While there are times when you may actually choose to implement such a loop, you usually want
a way to halt one either manually or automatically. We will rewrite the code a little to get it to
halt automatically after having annoyed you just a little.
Sub LoopForever()
Dim loopCount As Integer
Dim y As Integer
Do Until loopCount = 3
MsgBox "Looped " & y & " times."
loopCount = loopCount + 1
y=y+1
Loop
End Sub
the value of loopCount is used to exit the loop once it reaches a value of 3. How many times will
the message appear? No, not a trick question - the message will appear 3 times.
But what happens if we change it just a little bit?
Sub LoopForever()
Dim loopCount As Integer
Dim y As Integer
Do While loopCount < 4
MsgBox "Looped " & y & " times."
loopCount = loopCount + 1
y=y+1
Loop
End Sub
So I'll ask the question again: How many times will the message appear? In this case it becomes
a trick question. You'll see the message 4 times. And yet logic tells us that 3 is less than 4, but
the test must be done at the Do While statement and that means that we get an extra, sometimes
unexpected pass through the loop.
Again the message will be displayed 4 times because even though we've moved the test to the
bottom of the loop, we still have to get some value into loopCount that equals or exceeds 4 in
order to exit the loop. So be sure you know how many times your loop will execute if you are
depending on it to exit after a specific number of iterations. If we rewrite the last section like
this:
Sub LoopForever()
Dim loopCount As Integer
Dim y As Integer
Do
MsgBox "Looped " & y & " times."
loopCount = loopCount + 1
y=y+1
Loop While loopCount < 3
End Sub
Then the message will be displayed 3 times, presumably as you expected it to. You could also
change that last statement to:
Loop Until loopCount = 3
and get the message displayed 3 times.
We had to do a little more work but we got a lot of added functionality. Try changing the value
of constant testPhrase and see how it works. Just make sure you have at least one non-alphabetic
character in the phrase since we haven't tested to see if positionInString ends up becoming
greater than the number of characters in testPhrase.
Generally there's no accepted standard for which of the Do Loop types (While or Until) to use
other than your own personal preference. Typically you can write either type to accomplish the
same task and get the same result.
Decision Makers
There are two primary decision making tools in VBA: If...Then and Select Case. We can look
at the loop structures as decision makers also, but they are kind of indirect decision makers. The
If...Then, and its brothers If...Then...Else and If...Then...ElseIf...Else along with Select Case
are very definitely there to assist you in changing the path of the program or the logic of a
process; i.e., they help you make decisions about what to do next based on the result of
calculations or actions at a specific point in your process.
IF...THEN
This is the most basic of the decision makers. Using it assumes there is pretty much only one
test to perform and only one action to take if the result of the test is true. It can be written as a
one-line statement such as:
If X = 2 Then Y = 5
Very straight forward statement: if at this point in the process X equals 2, then set Y to 5. If X
does not equal 2 at this point, Y will retain whatever value it has at the moment.
A personal preference of mine is to make even this simple statement a "block" because I think it
makes the code more readable and understandable. This is exactly the same statement, but in
"block" form:
If X = 2 Then
Y=5
End If
This form also allows us to easily and clearly perform more than a single action based on the
result of the decision, like this:
If X = 2 Then
Y=5
Z=9
aStringVariable = "X was 2"
End If
So in this example, we perform three actions when we find that X has a value of 2. The End If
statement also gives us a clear view of what will be done when X = 2 by defining the end of the
If Then code block.
But what if we need to do one thing when X = 2 and do something else when it doesn't? Enter
the If...Then...Else statement.
Data Sources
There are lots of sources for data to work with inside of Excel:
Cells on worksheets
Files external to the Excel workbook (and I include things like queries to obtain data
from a variety of sources such as database files or from a networked location or internet
site)
The user!
There are a couple of things you need to keep in mind when getting data from any source:
You have to know where to find it, and what actions to take to get it into your VBA code
to work with, and
Remember that what you expect to get is not always what you actually do get. We'll
cover this aspect some more in a short discussion of data validation later on.
DATA FROM WORKSHEETS: INTRO
Within VBA you can get data from any cell or group of cells on any worksheet in any open
workbook. Later on I'll show you how to do this without ever leaving the cell that is currently
active on your screen.
You will need to know where to look for the information or how to find it, and unless you are
working in a fairly structured situation, you may need to perform some data validation on it
before trying to use it in your code.
DATA FROM EXTERNAL SOURCES
The possible external sources and their types is so varied that we can't really cover them all here.
You'll need to know how to either open any external data file such as a .txt, .dat or .csv file and
read from it and you'll need to know the format of the data in the file. Usually you have an idea
about these things before you begin writing the code to access the external files, so don't worry
about it at this time. Sometimes finding out what's in a file and how it's all laid out requires
some 'legwork'; that is, you may have to open the file and bring in the data without using Excel
and simply examine it to see what's what within it.
When querying databases you will probably have some guidance from those who created the
database and maintain it as to what tables and fields within those tables you are going to need to
reference to get what you want from it. This takes us into the realm of SQL (Structured Query
Language) and that's definitely beyond the scope of this book!
USER PROVIDED DATA
Working with data provided "on the fly" or in "real time" from the end user is almost an art. You
cannot EVER be certain that they'll provide the information you've requested in the form that
you need it or that it will even be the same kind/type that you asked for! User input data is
almost always in dire and desperate need of data validation before using it.
dataAccepted = False ' initialize to remain in the loop until a good entry is made
Do Until dataAccepted ' implied test of dataAccepted = True
userInput = InputBox$("Enter the Starting Balance for the account:", "Starting Balance", 0)
If IsNumeric(userInput) Then
'looks ok, at least it starts with numbers
dataAccepted = True ' so that we will exit this loop
Else
'oops, not looking very good
MsgBox "Please enter a dollar amount to continue..."
End If
Loop
acceptedInput = Val(userInput) ' get the numeric value of the validated/accepted entry
'... continue on to use acceptedInput in your code
End Sub
As you can see, we've set up a loop to keep asking the user for some numeric entry until we get
one from them. We use the Boolean flag, dataAccepted, to tell us when we think it is alright to
use what they entered later on in our processing.
dataAccepted = False ' initialize to remain in the loop until a good entry is made
Do Until dataAccepted ' implied test of dataAccepted = True
userInput = InputBox$("Enter the Starting Balance for the account:", "Starting Balance", 0)
If IsNumeric(userInput) Then
'looks ok, at least it starts with numbers
dataAccepted = True ' so that we will exit this loop
Else
'oops, not looking very good
MsgBox "Please enter a dollar amount to continue..."
End If
Loop
acceptedInput = Val(userInput) ' get the numeric value of the validated/accepted entry
'... continue on to use acceptedInput in your code
End Sub
You're probably going to ask "Well, teach, what do we do if userInput = ""?" My answer is "that
depends". It depends on how you want to handle it. You could toss up a prompt asking if they
wish to continue and put up the dialog again or you could put the default value of 0 into variable
userInput just as if they'd clicked [OK] or you might even ask them if they want to quit futzing
around with their checkbook for now and if so, shut down so they can restart everything later on.
ThisWorkbook.Worksheets("SysSheet").Range("A2") = "Client:"
ThisWorkbook.Worksheets("SysSheet").Range("B2") = Me!txt_ClientCompany
End Sub
Although I did not have to be as specific as I have been in this code, it definitely tells exactly
what to do with what:
ThisWorkbook. is optional usually. However since the person may be working on several
quotations in several workbooks, I use ThisWorkbook to tell VBA that I mean the worksheet
named SysSheet that exists in the same workbook that this code is being executed in.
Similarly, the Me! associated with the names of the two text boxes used in the example tells
VBA not to be confused by any other forms that may be open or any text boxes that it may see
laying around that have those same names.
Some of you may ask to please explain a little about how controls like the ComboBox,
checkboxes and option buttons in the first userform are referenced or tested in code. So I'll hit
them each quickly and then we'll move on.
Checkboxes and Option Buttons usually have one of two possible conditions: TRUE (has an x or
check in it or the button has a dot in the middle) or FALSE (checkbox is empty and same for the
circle of the option button). So you can write code like this:
If checkboxIncludeLadder = True Then
or
If optionButtonChoose1HPEngine = True Then
and take appropriate action based on the results of those kinds of tests.
As for the ComboBox, it has a couple of properties that can be used. You can use its .Text
property to get whatever selection was made in it verbatim. Or you can use its .ListIndex
Data Sources Page 38
Copyright © 2008 by J.L.Latham, All Rights Reserved.
Programming In Excel VBA by J.Latham
An Introduction Microsoft Excel MVP 2006-??
property to find out which item in the list was selected. The ListIndex values start at zero, so if
ListIndex = 0 it means that they chose the first item in the list. If they did not choose an item in
the list, the ListIndex value is a negative 1 (-1).
So How Do I Display or Remove a UserForm from the Screen?
To present a userform on the screen, you .Show it. Somewhere in your code you'll need a line
that uses the name of the form that you give it during design along with the .Show method, as:
UserForm1.Show
or
GetCustomerInformationForm.Show
You can simply write a macro to do it if you need to:
Sub ShowCustomerInfoForm()
GetCustomerInformationForm.Show
End Sub
There are two ways to remove a form from display. The code I presented earlier uses
Unload Me
which completely removes the form from memory. This has the side effect of also removing all
information that was entered into it at that time. I could write that line as Unload Me because it
was executed from within the form's code module. If I had needed to do that from some other
section of code I could have written it as:
Unload GetCustomerInformationForm
But you can simply hide the form from view which keeps it in memory and retains the
information that was last placed on it. Two ways of doing that:
First, from within the form's own code segment:
Me.Hide
Second, in some other code segment
GetCustomerInformationForm.Hide
And that's how you deal with UserForms. That is not to say that it is all that can be done with
forms and controls on them. Remember that this is an Introduction to things, not a definitive
bible covering every aspect of every possible command, object, function and feature in VBA or
Excel. I actually used different code in my project to move the data from the form onto the
worksheet, but what I wrote above will work and hopefully was easy for you to understand at
this point in the tutorial.
Ok, this one is more my project than yours – there‟s no work for you to do except examine the
code and observe the results. The project consists of two workbooks:
Project01_WB01.xls and Project01_WB02.xls
They are available by clicking the appropriate link (right-click and choose Save Target As) on
this page:
http://www.jlathamsite.com/LearningPage.htm
The code is all in Project01_WB01.xls (WB01) while the other workbook, WB02, contains data
that we want to move into WB01. There are three text boxes on the first sheet of WB01 that are
associated with VBA code. The first one activates a macro that was recorded while individually
copying each of the data items from WB02 into the 3rd worksheet in WB01.
To observe the difference in performance between the recorded macro and the custom code in
WB01, first try clicking the “Step 2” button. The object at this time is to simply see how long it
takes to copy a total of 167 entries from the WB02 into WB01. Obviously, both workbooks
must be open for this to take place.
The Step 2a and Step 2b „buttons‟ each run a version of custom written VBA code to achieve the
same results. The only difference between the two procedures is that one of them has a slight,
but probably not humanly noticeable speed advantage over the other. But they definitely have a
visible speed advantage over the recorded macro.
Other things to notice when examining the code in WB01 is that the recorded macro is absolutely
not robust or versatile: add another item of information in WB02 and it won‟t get copied over
into WB01; delete an item that‟s already in WB02 and you end up with a „hole‟ in the
information transferred over into WB01.
So now we see that not only is the custom code faster and more compact than the recorded
macro, but it is also more robust. It needs no further attention or maintenance no matter what
changes you make to the information in WB02.
The custom written VBA code demonstrates how to use objects in VBA to reference information
in an entirely separate workbook, and can easily be adapted to work for you with the same
workbook or across more than just two workbooks.
Often you don‟t have the luxury of working with another Excel file. But many applications have
the ability to either be saved as, or to export their information to what is known as an ASCII text
file. You‟re probably used to seeing them as .TXT files and they can be opened and read easily
with a program such as Microsoft‟s Notepad. Sometimes they are rather specially formatted
ASCII files that you see as .CSV files. CSV stands for Comma Separated Values. Actually
several different characters may be used besides a comma to separate groups of values, but the
name from the original use of the comma has stuck with them. Excel has built-in features to
import data from .CSV files, but other text files may not conform to those standards and you may
want to import those into Excel and nothing but custom code will do the trick for you.
Ok, this one is more my project than yours – there‟s no work for you to do except examine the
code and observe the results. The project consists of one Excel workbook and a text file with
sample data in it:
Project02.xls and Project02DataFile.txt
They are available by clicking the appropriate link (right-click and choose Save Target As) on
this page:
http://www.jlathamsite.com/LearningPage.htm
There are some useful snippets of code to take note of and possibly save for reuse. The module
named GetFilenameCode contains a routine that opens up the file browser window and will
return the full path and name of a file you select to the calling routine. This is definitely handy,
reusable code. I blatantly plagiarized that code from
http://www.cpearson.com/excel/GetFileName.aspx
No sense in reinventing the wheel unless you figure a way to make it turn faster and easier.
Chip's website, and others, provide fantastic resources like this at no cost to the user. But I do
believe that credit is always due to the benefactor, so Chip gets the plug from me along with my
gratitude for providing the code.
Within the ReadTextFileCode module, in the ReadATextFile process, there is definitely one line
that deserves some detailed discussion:
ActiveSheet.Range("A" & Rows.Count).End(xlUp).Offset(1, 0) = oneTextLine
The ActiveSheet is the one sheet that is currently selected in Excel. There can only be one
ActiveSheet at any given time.
The .Range(“A” & Rows.Count).End(xlUp) portion of the command says look in column A
beginning at the last possible row and go up the column until you find the end of cells that match
the general character of that cell. The „general character‟ being either empty or not empty. The
assumption here is that the last cell in the column is empty, so the command is going to find the
last cell in the column that is not empty. If the entire column is empty, it will return 1 for “the
first row is the end of this section”.
The .Offset(1, 0) portion says that once you‟ve found the end of the list, move down 1 row in the
same column. So this points at the next empty cell in the column, or if the column is entirely
empty, it points to row 2 of the column.
Application.ScreenUpdating = False
Set myTestSheet = ThisWorkbook.Worksheets("Sheet1")
myTestSheet.Cells.Clear ' delete any info on the sheet
Set baseCell = myTestSheet.Range("A1")
For LC = 65 To 90 ' values for A to Z
For IL = 1 To 1000 ' 1000 rows worth of each letter
baseCell.Offset(rowOffset, 0) = Chr$(LC)
rowOffset = rowOffset + 1
Next
Next
Set baseCell = Nothing
Set myTestSheet = Nothing
End Sub
GPP #2: Use Application.ScreenUpdating = False to improve performance. This command tells
Excel to hold off on actually sending updated data/changes to the screen. I've seen the use of this
command improve performance as much as 10 times without any other changes to the code at
all. Think about it: work done in 1 second instead of 10, or even 1 minute instead of 10 minutes.
Application.ScreenUpdating = False is almost a 'set it and forget it' command: When the end of
your Sub is encountered, Excel will automatically turn screen updating back on without any
action or code from you at all. Within a Sub it will remain in effect until you either exit the Sub
or you give a Application.ScreenUpdating = True command.
There's one catch to that automatic reset of screen updating - if your Sub calls other Subs, then it
will be turned back on when one of the other Subs exits unless you remember to set it back to
False after making the call(s).
'this Set will assign the range from A1 down to the last row in column A
'that has any entry in it. We don't have to worry about empty cells in
'the middle of the list any more!
Set seekInRange = myTestSheet.Range("A1:" & _
myTestSheet.Range("A" & Rows.Count).End(xlUp).Address)
'now we work through the individual cells in memory
For Each anyCellInSeekInRange In seekInRange
If Trim(UCase(anyCellInSeekInRange)) = SeekValue Then
'remember the address of the cell with the X in it
foundAtCell = anyCellInSeekInRange.Address
Exit For ' we found first "X" or "x"
End If
Next
endTime = Now()
'because we didn't update the screen, the current active
'cell is not 'visible', so we need to pull it up into view
Application.Goto Range(foundAtCell), True
MsgBox "It took " & Format(endTime - startTime, "ss") & " seconds to find X at " & foundAtCell
End Sub
I hope that all of this convinces you of the advantages of working with Object references to
objects in Excel. If it doesn't, then you probably might as well stop reading right here, because
you are going to see a lot more of them as we continue onward.
Programming With Excel Objects Page 47
Copyright © 2008 by J.L.Latham, All Rights Reserved.
Programming In Excel VBA by J.Latham
An Introduction Microsoft Excel MVP 2006-??
Keep in mind that any object that you can work with directly in VBA can be referenced by one
of these "in memory object references". This includes things like various shapes, controls,
queries, charts, chart elements, etc. But the end result of it all is that modifications you make to
those in-memory object representations are applied to the actual "see it on the screen" object they
represent, or to the unseen object (as hyperlinks or queries) in the workbook.
THE EXCEL OBJECT MODEL AS A REFERENCE
So how do you learn to reference these objects or what their 'family' (technically a 'Collection' in
Excel) is? There are a couple or three of ways to do that. One of the more direct methods is to
use the Excel Object Model as a reference. So, where the heck is it at?
There are a couple of ways to modify what we just did to find the first empty cell in the column
of data.
Method #1: Take the value of lastRow and add 1 to it. That would be the row number of the next
available empty cell in the column.
Method #2: make the addition part of the statement itself.
lastRow = ThisWorkbook.Worksheets(“SheetName”).Range(“A” & Rows.Count).End(xlUp).Row + 1
You can even modify the statement with the .Offset() option to do it:
lastRow = ThisWorkbook.Worksheets(“SheetName”).Range(“A” & Rows.Count).End(xlUp).Offset(1, 0).Row
Enough about finding those particular unique entries in a column. Now we‟ll look at doing
much the same thing for rows.
Excel 2007
Where can I find the menu commands in Excel 2007
Create and mail PDF files with Excel 2007
Use VBA SaveAs in Excel 2007
Copy sheet security dialog in Excel 2007
Sheet Direction in Excel 2007
Reverse compatibility problem of the old ATP functions
Macros are disabled when you open password protected workbooks
Shapes and VBA code in Excel 2007
Filtering by the Active Cell's Value, Font Color or Fill Color in Excel 2007
Help: Different Excel file formats and Excel versions
Disable Excel 2003 Menu Accelerators keys in Excel 2007
Table Tools in Excel 2007
VBA code examples for Tables in Excel 2007 or a List in Excel 2003
Copy/Paste/Merge examples
Copy to a database sheet on the next empty row
Merge cells from all or some worksheets into one Master worksheet
Create a summary worksheet from all worksheets (formulas with VBA)
Create a link to or Sum a cell in all worksheets (worksheet functions)
Merge data from all workbooks in a folder (1)
Merge data from all workbooks in a folder (2)
Merge data from all workbooks in a folder: Add-in
Create a summary worksheet from different workbooks (formulas with VBA)
Merge data from all workbooks in a folder to a txt file
Copy every TXT or CSV file in a new worksheet of a newly created workbook
Merge all CSV or TXT files in a folder
Copy a range from closed workbooks (ADO)
Copy a range from closed workbook (Local, Network and on the internet)
Copy data from an Access database into Excel with ADO
Change cells or range in all workbooks in a folder
Copy records with the same value in a column to a new sheet or workbook
VBA code examples for Tables in Excel 2007 or a List in Excel 2003
Delete/Hide/Disable examples
Delete row if a specific value exist
Delete or Hide Objects/Controls on a worksheet
Disable command bars and controls
SpecialCells limit problem
Disable key or key combination or run a macro if you use it
Weeknumber/Dates
Use the Calendar control to fill in dates
Week numbers
ISO Date Representatation and Week Numbering
Help information
Help Context IDs for Excel 2000, 2002, 2003 and 2007
Where do I paste the code that I want to use in my workbook
How do I create a PERSONAL.XLS(B) or Add-in
Other pages
Print tips for Excel
Test if Folder, File or Sheet exists or File is open
Find last row, column or last cell
Change formulas to values
Find value in Range, Sheet or Sheets with VBA
Cleaning "Dirty" Data
Lotus Transition Formula Evaluation Errors
Analysis ToolPak Translator 7.0
Keyboard Shortcuts
C
Macros, Copy to a workbook video
Charting - Jon Peltier's Site Index Macros Prompt, Enable or Disable (FAQ) video
Charting Links Macro Toolbar 24-Dec-05
F
Topics Index
FAQs, Excel - Application and Files
FAQs, Excel - Dates and Times Trailing Minus Signs
FAQs, Excel - Index
FAQs, Excel - Macros, VBA
FAQs, Excel - Pivot Tables and Pivot Charts 09-Oct- Used Range, Reset (FAQ)
06
FAQs, Excel - Worksheet Functions and Formats UserForm, Create a Video
UserForm with ComboBoxes 23-Jan-06
File with that name is already open (FAQ)
File size, large (FAQ) VBA Code, Copy to a workbook
Fill colour doesn't work (FAQ)
Video Index
Fill pattern doesn't print (FAQ)
Video Instruction Clips 01 10-May-08
Video Instruction Clips 02 10-May-08
Filter, Advanced Video Instruction Clips 03 13-May-08
Filter, AutoFilter Video Instruction Clips 04 23-May-08
Video Instruction Clips 05 01-Jun-08
Video Instruction Clips 06 updated 25-Jul-08
Video Instruction Clips 07 updated 31-Aug-08
Video Instruction Clips 08 updated 30-May-09
Video Instruction Clips 09 05-Feb-09
Video Instruction Clips 10 19-Feb-09
VLOOKUP function Video
A M
Absolute And Relative Cell References
Activating Excel From Other Applications Macro-Sheet Function, Calling
From Worksheet Cell
ActiveCell, Highlighting Macros, Adding or Deleting With
VBA Code
Add-Ins, Automation, Creating Macros, As Opposed To Functions
Add-Ins, COM, Creating With VB6 Macros, Ensuring Macros Are
Enabled, Technique 1 (Sheet
Visibility)
Add-Ins, Creating Macros, Ensuring Macros Are
Enabled, Technique 2
(Calculations With Errors)
Add-Ins, Installing And Loading Macros, Running From Worksheet
Cell
Add-Ins And Utilities, Third Party Matrix To Vector Formulas
Age, Calculating Maximum Values, Persistent
ALT, SHIFT, and CTRL Testing State Of Key Me Reference, Self-referencing an
instance of a class
Analysis Tool Pack (ATP), Installing Menu Items, Creating Manually
Analysis Tool Pack, Calling Function From VBA Menu Items, Creating With VBA
Code
AnyXML, Allowing optional and arbitrary XML Menu Items, Creating For The
content with an XSD Schema VBA Editor
API Functions, Getting Error Information Merging Lists Without Duplicates
Application Events Minimum And Maximum Values
Application Shutdown, Detecting And Taking Action Minimum And Maximum Values,
Persistent
Application-Level Names Missing References In A VBA
Project
Arguments, Passing ByVal And ByRef Modified File, Returning The Most
Or Least Recently Modified File In
A Folder
Array Formulas, Described Modules, Adding And Deleting
With Code
Array, Converting To Columns Modules, Adding descriptions for
the Object Browser
Array, Testing If Allocated Months, Calculating Fractional
Months
Array, Testing If Sorted Most Or Least Common Entry In A
List
Arrays, Determining Data Type Of Moving A Form With The Window
Arrays, Number Of Dimensions Multiple Monitors
B
Banding, Color Banding With Conditional Formatting
O
Birthdays And Age
Blank Cells, Eliminating Objects, Declaring
Blank Rows, Deleting Objects, Sorting Arrays Of Objects
Blinking Text Objects, Connected And
Disconnected
Bracket Pricing, Formulas For OnTime Method In VBA
Browse For Folder On Error handling
Built-In Document Properties Optimizing VBA Code
Button Image, Custom Pictures Optional Parameters To A
Function
ByRef and ByVal Parameter Passing Optional And Arbitrary XML
defined in an XSD Schema
Option Explicit
Order, Reversing Cell
Ordinal Numbers In Excel
C
Overtime Hours In Timesheets
CALL Worksheet Function
Caption of a Window and the Hide Extensions
setting P
Case, Converting Text To Upper or Lower Case
Cell Contents, Displaying Hidden Characters ParamArray parameters to a VB
Function
Z
K
Zero Values, Ignoring In Functions
Keyboard Shortcuts Zip File, Saving A Workbook As A
Zip File
L
Last And First Names, Extracting From A String
Last Modified File, Finding In A Folder
Last Update Time Of Cell Or Range
Latitude And Longitude
Leap Year, Determining
Least Or Most Common Entry In A List
Legal Information About This Site And Its Contents
ListBox, Support Procedures For A ListBox control
Lists, Counting Distinct Entries
Lists, Extracting Unique Entries
Lists, Entries Common To Two Lists
Lists, Entries On One List And Not On Another
Lists, Highlighting Duplicate Entries
Lists, Merging Without Duplicates
Lists, Testing For Duplicate Entries
Lists, Reversing and Transposing
Lists, Minimum And Maximum Values
Lookups, Left Lookup (alternative to VLOOKUP)
Lookups, Formula To Look Up Data In A Table
Lookups, Flexible. Alternative To VLOOKUP
Lower Case, Converting Text To Lower Case