Programming in Excel VBA
Programming in Excel VBA
in
Microsoft Excel VBA
An
Introduction
by J.Latham
Microsoft Excel MVP 2006-??
The most current version of the book may be downloaded, free of charge, from:
http://www.jlathamsite.com/LearningPage.htm
HTU
UT
Look for the link to the .pdf document just below the heading "Introduction to VBA Programming". I
recommend right-clicking the link and choosing "Save Target As" to get a copy of it onto your system.
In October 2012, a new publication was placed on the website. While not designed specifically
to be a companion to this introduction, I believe that many of you that are serious about
programming in Excel VBA will find it useful. It is also available through the above link,
through this direct link to it:
Bullet-Proofing Your Excel VBA Code
It also has a companion workbook demonstrating the effects of scope in Excel VBA.
SlicesOfPi.xls
And keep your eyes out for an introduction to Debugging that is now a work in progress.
Table of Contents
OVERVIEW ...................................................................................................................................... V
Why ............................................................................................................................................ v
What ........................................................................................................................................... v
Who ............................................................................................................................................ v
How ............................................................................................................................................ v
Anticipated User Skill Requirements ...................................................................................... v
Copyright Acknowledgments.................................................................................................. vi
Creating this Guide .................................................................................................................. vi
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
T
Table of Contents
Page i
Table of Contents
Page ii
Table of Contents
Page iii
by J.Latham
Microsoft Excel MVP 2006-??
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 ................................................................................ 25
Figure 16 InputBox$() Example ................................................................................................... 35
Figure 17 InputBox$() Validation Failed Message ...................................................................... 35
Figure 18 Plain Vanilla MsgBox$() Displayed ............................................................................ 37
Figure 19 MsgBox Used to Obtain User Input ............................................................................. 37
Figure 20 Multi-Control UserForm .............................................................................................. 38
Figure 21 UserForm With Text Entry Boxes ................................................................................ 39
Figure 22 - Define Name Dialog: Excel 2003 .............................................................................. 53
Figure 23 Name Manager: Excel 2010 ......................................................................................... 54
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
TU
UT
Table of Contents
Page iv
by J.Latham
Microsoft Excel MVP 2006-??
Overview
0B
WHY
16B
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 dont 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
17B
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
HTU
UTH
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
18B
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
19B
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.
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).
Page v
by J.Latham
Microsoft Excel MVP 2006-??
21B
This document was created using Microsoft Word and Excel 2003, along with the Microsoft Office 2007 provided
publish as .pdf feature to generate the final document.
Graphic screen capturing was performed using SnagIt from TechSmith.
COPYRIGHT NOTICE: This document in all forms is Copyright by Jerry L. Latham, 2008, 2009,
2011. All rights are reserved. Readers are granted permission to make copies for their personal or
educational use and even corporate/commercial use, but in no instance may the document or portion or
portions thereof be used as part of or as the totality of any package that is distributed or provided for
profit or other gain. This book is FREE and if someone charged you money for it, or charged you
money for a package that it is any part of, they stole from you and they stole from me. Those people are
thieves.
The most current version of the book may be downloaded, free of charge, from:
http://www.jlathamsite.com/LearningPage.htm
HTU
UT
Look for the link to the .pdf document just below the heading "Introduction to VBA Programming". I
recommend right-clicking the link and choosing "Save Target As" to get a copy of it onto your system.
In October 2012, a new publication was placed on the website. While not designed specifically
to be a companion to this introduction, I believe that many of you that are serious about
programming in Excel VBA will find it useful. It is also available through the above link,
through this direct link to it:
Bullet-Proofing Your Excel VBA Code
It also has a companion workbook demonstrating the effects of scope in Excel VBA.
SlicesOfPi.xls
Page vi
by J.Latham
Microsoft Excel MVP 2006-??
What is VBA?
1B
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 3 rd
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.
P
VBA can probably be best described as an object-based (but not a true object oriented) language
that is event driven. Lets 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 isnt 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 dont have code associated with
them, and thats to be expected; something doesnt 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.
23B
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.
24B
While you may use constants and variables in your code that seemingly dont 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.
Page 1
by J.Latham
Microsoft Excel MVP 2006-??
The Excel VBA IDE (Integrated Development Environment) has not changed in quite some
time. This is a good thing the interface in Excel 2007 is the same as it was in Excel 2003, 2002
(XP), and even back to Excel 97 , and that means that no time is wasted for programmers in
learning a new interface just to be able to continue to use a language they are already familiar
with. There are 5 major areas of the IDE and I like to work with all of them visible.
Page 2
There are also other fast ways to open the VBE to specific areas without first opening the entire
project as these two methods do. We will discuss those when we talk about code that deals with
Workbook and Worksheet related event processing.
Not all 5 major areas of the VBE may be visible when you first open it. The [View] VBE menu
option allows you to choose which of them are visible.
The VBE menu and
normal icon toolbar.
Page 3
by J.Latham
Microsoft Excel MVP 2006-??
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 youve opened them,
simply click the classic close window [X] in the upper right
corner of the window.
Rather than trying to make you remember what each and every window contains, what its used
for and how to make them work for you, we will cover using them during our discussions on
actually writing code and accessing objects during code development.
TO BE EXPLICIT OR NOT
Well, lets be frank about this: we are all adults (all programmers are performing an adult task
and so, regardless of their physical age, we will give them adult status and that does mean that
they should act as responsible adults, i.e. no intentional malicious coding allowed). Since we are
now all adults, we can be Explicit.
26B
Your initial view of a code module may not contain the Option Explicit statement at the
beginning of it. It should quite simply this is your first step to responsible coding through
the use of accepted Best Practices.
Option Explicit is a directive to the compiler that says that all user defined constants and
variables must be declared before actually using them in the code. The up side of using Option
Explicit is that errors in your code due to typographic errors or reuse of a variable as the wrong
type are greatly reduced and when it does happen, the problems are more easily identified. The
down-side? Just that you have to take the time to go back and declare constants or variables that
you find you need during code development.
Page 4
Page 5
by J.Latham
Microsoft Excel MVP 2006-??
Ill bet you thought that all code modules were created equal. Not true code modules dont
have any Constitutional Rights, although they do have to follow the rules of design requirements
imposed by Microsoft and the compiler.
GENERAL PURPOSE CODE MODULES
These are code modules youll bring into existence and can contain code to do almost anything
of a general purpose nature. Examples of code that might appear in them would be code that
responds to shapes or command buttons you might put on a worksheet; code to respond to
custom menus you might develop, user defined functions (UDF) that you develop to perform
actions and calculations by way of using the name of the UDF in a worksheet formula just like a
built-in Excel worksheet function.
27B
Oh, By the Way Macros you record are placed into general purpose modules. Recording
macros during different sessions with the workbook results in numerous modules that may
contain as few as a single procedure (macro) in it. This results in being quite wasteful of
resources. All macros recorded during a single session are typically placed into a single module.
To create a new general purpose module you can use the [Insert] | Module
option from the VBE menu toolbar:
Page 6
Workbook Events
85B
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 doubleclicking the ThisWorkbook object in the VBAProject window. Youll get a display similar to
this
If you use the left pulldown of the workbooks code module youll see that there is a specific
Workbook entry. If you choose that item, the VBE will automatically insert a stub (just the
beginning declaration and end statement for the procedure) for the Workbook_Open() event.
You can delete that entry if you dont need code to deal with something you want to happen
when the workbook is opened.
With your cursor placed inside of any Workbook related procedure, even just a stub, you can
then use the pulldown on the right to find a list of all the available event handlers for the
workbook. And it is quite a list.
Types of Code Modules
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 7
Page 8
Worksheet Events
86B
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. Youll get a display similar to this
For worksheets, when you choose the Worksheet item in the left pulldown list, the default event
is the Worksheet_SelectionChange(ByVal Target As Range) event. This even triggers any time
you make a new selection on the sheet such as simply moving to another cell. The new cell
becomes the selection, and thus youve had a selection change.
As with the Workbook events, you can now get a complete list of Worksheet Events available to
be programmed against by using the right-side pulldown (indicated by (Declarations) in the
graphic). This list is much shorter than the Workbooks list, but even these 9 (from Excel 2003)
provide considerable versatility in dealing with worksheets. Out of the list, the Change() event is
probably the one that most often has code associated with it. A Change() occurs when a user
alters the contents (value) of one or more cells on the sheet. Worksheet formula recalculations
dont trigger this event, but they do trigger the Calculate() event.
The Target and Cancel Objects
87B
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
Types of Code Modules
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 9
Class Modules
8B
Quite frankly were 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
89B
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.
Page 10
by J.Latham
Microsoft Excel MVP 2006-??
Code modules contain code, and that code is placed into procedures, and procedures fall into two
categories: Sub (or subroutines) and Function(s).
FUNCTIONS
The difference between a Sub and a Function is simply that a function can return a value to the
procedure that called it. That procedure can be another Function, a Sub or even to a worksheet
cell. When it is done using a worksheet formula, the Function is known as a User Defined
Function, or UDF. Potentially all Functions are UDFs.
31B
One other distinction between Functions and Subs is that (generally) Functions can only affect a
single cell in a workbook, while Subs can do their work and affect almost any aspect of a
workbook or worksheet. When it is used as a UDF, it can only affect the cell that it is called
from; it cannot alter the contents of other cells.
A Function starts with its declaration:
Function functionName (argument1 As Type, argument2 As Type) As fType
Where Function is a reserved word declaring the start of the definition of the function.
functionName is the name you assign to the function.
Within the parenthesis you define the list of arguments and their types that are to be passed to the
function 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:
Function noArgumentFunction() As Boolean
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 functions
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
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 11
Page 12
by J.Latham
Microsoft Excel MVP 2006-??
Ready for your first programming lesson? Yeah, I know, its about time!
In the process of writing code you are going to find the need to be able to remember things,
compare things and change things. These things are values. You will also find times that you
want to make sure that a value you use in several places in your code does not change. VBA,
and all high level programming languages provide ways to deal with these needs. You may
declare a constant or a variable several different ways and you can decide just exactly what kind
of information that constant or variable may hold.
DATA TYPES
Before we jump into creating our constants and variables, lets discuss Typing. VBA has several
data, well, types that it can deal with. Being specific with the type of data that a constant or
variable is to hold can improve performance and reduce unexpected errors of a very strange and
unexpected nature. For a complete list of data types, search the VBE Help for the topic Data
Types. For once, Help actually makes sense and offers real help to you by listing the numerous
types that it recognizes. These include (refer to the VBE Help topic data type summary for a
complete and current list for the version of Excel you are using).
34B
Page 13
by J.Latham
Microsoft Excel MVP 2006-??
String: Variable Length zero (empty string) to approximately 2 billion characters. (10 bytes
of memory plus the length of the string)
String: Fixed Length length of the string when declared, 1 to approximately 65,400. (1 byte
per character)
And you thought I was kidding about strings coming in two lengths. To continue and now we
get to some that probably wont make quite as much sense to you as the list has so far.
Object a reference to an object that you declare. When a variable is declared as an object it
can take on the attributes of any legitimate object when you use the Set command to assign it to
a specific type of object. An object is much like the Variant type that you are about to see. (4
bytes)
Variant any variable that is not defined as a specific type is by default of type variant. A
variant can take on the attributes of any other type depending on how values are assigned to it.
Generally you should refrain from declaring variables as type Variant, however sometimes it is
actually required that a Variant be used in some circumstances. Somewhat like strings, Variants
come in two variations (yeah, now I am playing word games)
Variant with numbers a variant can take on any value up to that of type Double. (16 bytes)
Variant with text characters a variant has the same limits as a variable length String type, but
it takes 22 bytes plus the length of the text in memory.
Finally, we get to the truly catch-all-nothing-else-will-do type, the user defined type! Yes, you
can define your own type. These are special cases where you use a combination of other types to
define your own. We will use at least one user defined type in our learning in time. For now
picture this: you create a user type that you call EmployeeRecord and it consists of a type that
can hold some text, some numbers, a date or two and even a currency value, any of which can be
referenced as a property of a variable that you declare as type EmployeeRecord.
Oh crap! Ive forgotten an entire application worth of types!! For each application that VBA is
implemented in, any object in that application can be used as a type. So in VBA for Excel you
can declare variables as specific objects such as the Application itself, a Workbook, a
Worksheet, a Range, a chart, a style, and just about anything else that exists in the Excel world.
We will definitely deal with this kind of assignment of type later on Excel VBA is just a
cripple if we dont make use of this incredible ability.
Alright, lets declare some variables and constants and discuss what we might do with them. But
we are going to do it all for real and write some code to use the constants and variables that we
define. We will start on the next page.
Page 14
Procedure names should be at least somewhat meaningful and hopefully will give some insight
about their purpose or what theyre going to do. So naturally we will call this procedure
MyFirstProcedure. Go ahead and get it started click anywhere in the code window below the
Option Explicit statement. If you dont have an Option Explicit statement at the top of the code
module then start reading back at page 1, please.
This procedure will show you one way of getting an entry from the user, do something with that
data and both show the result on a worksheet and in a message to the user.
Sub MyFirstProcedure()
'this procedure accepts a numeric input from the user
'calculates that value raised to a specific power
'and places the result on a worksheet and also
'displays it in a message box to the user.
'***declare a constant to hold the name of the sheet
'that will receive the results of our calculation
'this lets you call this procedure from anywhere at
'any time and always have the result go to a
'specific sheet. If the sheet's name changes
'you can change it here and the code will
'continue to function in the same way.
Const dataSheetName = "Sheet1" ' name of sheet
Const raiseToPower = 2 ' square the number
Dim theNumber As Integer ' from user
Dim theResult As Integer ' calculated value
'get the number from the user.
'InputBox accepts any input, even numbers and dates,
but it accepts it as text which we may have to massage.
'so we will have to make sure that they
'entered a number or something that looks like one
'we will display a prompt, a title and create a default
'value of zero
'because theNumber has been declared as an integer, if the
'user enters something non-numeric, a run-time error will
'take place. If you experiment with that and get a
'runtime error 13 (type mismatch), just click the [END]
'button to bring things to a safe stop.
theNumber = InputBox("Enter a whole number", "Integer Input", 0)
'the ^ symbol means "raise to power"
theResult = theNumber ^ raiseToPower
'put theResult on a worksheet in cell A1
Worksheets(dataSheetName).Range("A1") = theResult
'display an explanation to the user in a message box
MsgBox theNumber & " raised to the power of " & raiseToPower & " = " & theResult
End Sub
Procedures: Sub and Function
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 15
by J.Latham
Microsoft Excel MVP 2006-??
Running your first procedure. There are a couple of ways
to test your code at this point. But before just trying it out,
its a good idea to make a couple of desk checks. Read
through the code again to see if you notice any obvious
errors, such as perhaps typing * (multiply) instead of ^
(raise to power). The VBE can also help you with a desk
check step, and its very critical of your code and can help
find problems very early on. From the VBE menu choose
[Debug] | Compile VBAProject.
If it doesnt find anything wrong, it will simply blink and
do nothing else it doesnt give all clear message. If it
does find a problem, it will highlight the first offensive
line that it finds and tell you what the problem is.
Fix the problems and repeat the process until it doesnt
report any more errors to you.
One thing you may notice both in the code above and in the VBE itself is that some words and
phrases are in one color while others are in a different color. This is by design and is to help you
read and interpret the code. VBA reserved words are shown as blue text, while comments are
shown as green text, while pretty much everything else is in black. Your editor may be set up to
show these things in different colors, but there will be differences in colors for the different
meanings of the code pieces. There is one more color that you may see from time to time red
text indicates a line of code that VBA has determined to contain one or more errors.
RESERVED WORDS
You cannot use words unique to the VBA language as the names for your own constants and
variables. The list is pretty long, youll learn what you can use and what you cannot during your
coding efforts. Words like For, Next, Do, Loop, Until, Dim, Const, InStr are reserved for the
language and you cant use them except as the instructions that they are. It is even considered
bad form to use a reserved word as part of a constant or variable name because it can confuse
anyone reading the code later, so while intNext is a valid name, it is an unwise one to use; but a
name like intNextNameInList would probably be a good one to use.
36B
X = X + 1 add one to X
Procedures: Sub and Function
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 16
So what can we do about such situations? VBA provides the On Error statement to help deal
with both anticipated errors and those not so anticipated. Using one form of it, we can change
our code just a little and keep it from failing as dramatically and allow the user to recover from
the error.
Page 17
Page 18
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
procedures 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
91B
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 weve 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!
Page 19
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
93B
One question that comes up from time to time is why use constants at all why not just use
their value(s)?. Ill 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 youve 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).
Page 20
by J.Latham
Microsoft Excel MVP 2006-??
Weve already discussed one good programming practice that is beneficial: having the VBE
automatically require declaration of constants and variables before their use.
Most good programming practices fall into the category of either good common sense or of
following a generally accepted standard, as with the use of the single-quote/apostrophe as the
beginning of a comment.
Good programming practices will improve your chances of actually writing Good Code.
WHAT IS GOOD CODE
There are probably as many definitions of good code as there are programmers. My definition:
Good Code is code that performs the task required and does so reliably. Good Code is also
maintainable.
40B
Some examples of Good Code at work in this day? WinZip. IrfanView. Microsofts Calculator
and Notepad. They do what theyre designed to do, they do it simply, and they do it reliably.
Im sure you can think of many more examples, just as you can think of programs written with
bad code that are far less than you expected when you acquired them.
Good Code also takes the user into consideration making things easier for them, performing the
application's tasks with a minimum of fuss, bother and annoyance. This is the human-machine
interface side of code design and development. Working closely with your client or studying
your intended audience can help you design an effective, usable interface for your application.
GOOD PROGRAMMING PRACTICE #2
Be consistent. If you dont follow any published standards for conventions such as commenting,
constant/variable naming, source code listing formats or others, then at least be consistent within
your own code in the way you do these things. This will make your code more readable and
understandable to you, and will tend to making extending the code to include new features,
modify old ones and simply fix bugs than if you do things one way today and some other way
the next. That is not intended to keep you from changing the way you do things as you discover
better ways to do them.
41B
Page 21
by J.Latham
Microsoft Excel MVP 2006-??
Looping Structures
7B
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.
GPP #3:
Keep the amount of work inside of a loop to a minimum. If there is something that can be done
outside of the loop before starting it, do it outside of the loop.
43B
For example let us assume you want to take a list of numbers you have in a range and increase
those values by some percentage that you have stored. You could code it like this:
For Each anyValue In listOfValues
anyValue = anyValue * (1 + percentIncrement)
Next
The problem with this is that each time through the loop, the value of 1 + percentIncrement must
be recalculated. You can increase the efficiency of that loop by calculating that value before
entering the loop, as:
tempValue = 1 + percentIncrement
For Each anyValue In listOfValues
anyValue = anyValue * tempValue
Next
FOR NEXT LOOPS
The simplest and oldest loop structure in Basic is the ForNext loop. The general form, or
syntax, of the command is
4B
Looping Structures
Copyright 2008, 2014 by J.L.Latham, All Rights Reserved.
Page 22
Looping Structures
Copyright 2008, 2014 by J.L.Latham, All Rights Reserved.
Page 23
Page 24
by J.Latham
Microsoft Excel MVP 2006-??
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:
What does this tell us? Simply that the test for the counter value is made at the For statement,
not at the Next statement. Generally this isn't information of great interest, but it can be handy to
know at times.
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.
Looping Structures
Copyright 2008, 2014 by J.L.Latham, All Rights Reserved.
Page 25
In exchange for this versatility, you have to do a little more work in the form of helping to
control when the loop terminates. Consider this simple loop.
Sub LoopForever()
Do
MsgBox "Pete and Repeat were in a boat. Pete fell out. Who was left?"
Loop
End Sub
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. The technical reason is that the loop started at ZERO!
Looping Structures
Copyright 2008, 2014 by J.L.Latham, All Rights Reserved.
Page 26
by J.Latham
Microsoft Excel MVP 2006-??
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.
Looping Structures
Copyright 2008, 2014 by J.L.Latham, All Rights Reserved.
Page 27
Looping Structures
Copyright 2008, 2014 by J.L.Latham, All Rights Reserved.
Page 28
Do
'your code within the loop will run (execute) until you take some action within the code to force it
'to exit the loop using an Exit Do statement.
'without such a control, it becomes an "infinite loop".
Loop
--Do Until testCondition
'your code within the loop will execute only while the testCondition is FALSE.
Loop
--Do
'the code executes at least one time and will continue to execute within the loop as long as the
'testCondition is FALSE
Loop Until testCondition
--Do While testCondition
'your code within the loop will run (execute) only while the testCondition is TRUE.
Loop
--Do
'the code executes at least one time and will continue to execute within the loop as long as the
'testCondition is TRUE
Loop While testCondition
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.
Looping Structures
Copyright 2008, 2014 by J.L.Latham, All Rights Reserved.
Page 29
by J.Latham
Microsoft Excel MVP 2006-??
Decision Makers
8B
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:
48B
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.
Decision Makers
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 30
If X = 2 Then
Y=5
Z=9
aStringVariable = "X was 2"
Else
Y=1
Z=3
aStringVariable = "X was not 2"
End If
So here we are saying that when X = 2, we set Y, Z and aStringVariable to particular values, but
if X is some value other than 2 then we set those same variables to a different set of values.
We can extend this decision making even farther using ElseIf along with what we've already
seen.
IF...THEN...ELSEIF...ELSE
Using this combination we can test for different values of a particular item. For this example, we
need to set Y, Z and aStringVariable to specific values when X is either 2 or 3, and another set of
values when it is not 2 or 3.
50B
If X = 2 Then
Y=5
Z=9
aStringVariable = "X was 2"
ElseIf X = 3 Then
Y=0
Z = 99
aStringVariable = "X was 3"
Else
Y=1
Z=3
aStringVariable = "X was neither 2 nor 3"
End If
You may actually have many ElseIf ... Then statements before the final Else statement, making
this a multi-conditional decision maker. But for the times when you have many decisions to
make based on the value of one (or more) variable value(s), the Select Case statement is more
efficient.
Decision Makers
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 31
To show how it can work, we will use the same situation that we had for the last example in the
If...Then variants section.
Select Case X ' base our decision on the value of X
Case Is = 2 Then
Y=5
Z=9
aStringVariable = "X was 2"
Case Is = 3 Then
Y=0
Z = 99
aStringVariable = "X was 3"
Case Else
Y=1
Z=3
aStringVariable = "X was neither 2 nor 3"
End Select
You can have any number of Case Is type statements, allowing you to make decisions based on a
large number of possible values for a variable.
You do not HAVE to have a Case Else statement, but it is wise to have one. It doesn't even have
to do anything, but having a "do nothing" section tells others reading the code later that no action
is taken if a value doesn't meet one of the stated values. Here's a "do nothing" setup:
Select Case X ' base our decision on the value of X
Case Is = 2 Then
Y=5
Z=9
aStringVariable = "X was 2"
Case Is = 3 Then
Y=0
Z = 99
aStringVariable = "X was 3"
Case Else
' no action required or desired when X is not 2 or 3
End Select
The Select Case block always ends with the End Select statement.
Decision Makers
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 32
by J.Latham
Microsoft Excel MVP 2006-??
Data Sources
9B
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.
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.
53B
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.
54B
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 33
They type it into cells on worksheets and you read it from there - which goes back to the
earlier section on DATA FROM WORKSHEETS
Data entered by the user in response to the use of the InputBox$() function in VBA. This
is useful for getting single quick input from the user when you need it.
Evaluating the user's response to a MsgBox$() function that uses several buttons, as
[Yes], [No] and/or [Cancel] on it to allow the user to indicate their response to the prompt
you have provided as part of the message displayed. Very little data validation is needed
with this one.
Inputs provided on a UserForm. A UserForm allows you to get many inputs at once from
the user. This is a good way to gather lots of information at once, but you're going to
need to do data validation on a lot of it of some type before actually making use of it.
We'll take some quick looks at the last 3 of these in this section, nothing in great detail, but
hopefully enough to give you an idea of the abilities of each of those 3 methods of obtaining
information from the user.
INPUT USING INPUTBOX$()
In VBA code the InputBox$() function is coded as shown below. For this example we are going
to ask the user to enter what we plan on using as a starting balance for a worksheet that is set up
to act as a checking account program of some type. So we are expecting a numeric input that we
will want to use as money (Currency).
5B
Sub GetACurrencyEntry()
Dim dataAccepted As Boolean ' a flag to tell us when we think the input is good
Dim userInput As Variant ' use variant to accept any type of entry the user may provide
Dim acceptedInput As Currency ' we will store the validated/accepted amount in this variable
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.
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 34
You can see where the three pieces of information were used when the line of code was
executed. If the user just presses [Enter] or clicks the [OK] button at this point, we get zero ( the
default value we provided) as the starting balance.
But if they don't enter something that looks like numbers, they will get a reminder message and
the dialog will be shown to them again:
But there are 2 situations that can come up here that we haven't taken into consideration in our
data validation: The user clicks the [Cancel] button or the user clicks on the close dialog X.
In both of those cases we get a zero length string back into variable userInput, not a zero or
anything else. We have to expect this to happen, look for it, and decide what to do if it happens.
That's more of the data validation process. Here is the code segment with a test for this situation
added to it:
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 35
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 36
Normally MsgBox() just puts up a message with an [OK] prompt and continues to process after
the user hits the [Enter] key or clicks the [OK] button. Code for such a thing might look like
this:
MsgBox "We are on page 34 of the tutorial.
vbOkOnly,"Checkpoint"
But what if we want the user to make a choice right now? We could change it a little bit and ask
if they want to continue reading or take a break. You can 'capture' and evaluate the user's
response to a MsgBox() by forming it as a function and using it as a test, like this:
Sub Checkpoint()
If MsgBox("We are on page 34 of the tutorial. Would you like to continue", vbYesNo, "Checkpoint") = vbNo Then
Application.Quit ' close Excel!!
End If
'just continue on here...
End Sub
By enclosing the prompt, button choices and title within () we have turned it into a function that
returns a code associated with the button they click. It would look like this on screen:
vbOkOnly, vbYesNo and vbNo are constants automatically available within VBA - you don't
have to predefine them anywhere in your own code. There are others that can be used with
MsgBox also, such as vbExclamation, vbCritical, vbYesNoCancel and some that let you
determine which button on a multi-button message is the default (is used if they just hit the
[Enter] key).
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 37
I chose this one because it uses many of the possible controls you can use on a user form. It
starts off using a ComboBox control to present a list of possible models of a piece of equipment
that the user can select from to begin to build up a cost for the item. The astute observer will
notice that everything except that ComboBox is disabled right now. That means that the user can
only choose a Model ID at this point. That is part of my own data validation here: they can't
choose pieces of an equipment item without first telling what equipment item they are going to
be working with. Once they choose from the list, everything else gets set up to hold and accept
legitimate values from the user. All of the other controls on this form really need no further data
validation because the form itself and the way option buttons and check boxes within groups
work does it for me automatically. What I want you to see here is the variety of controls you can
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 38
Each of the text entry boxes on this form has a unique name, just as each of the controls on the
other form do. That allows us to work with them in the VBA code. Actually on this form there's
not much done in the way of serious data validation because most of the entries are things that
we pretty much don't have an idea of what they should look like. But we can check to make sure
that something was entered into any areas that we consider mandatory information, and we might
check that the zip code looks like a zip code or that phone numbers look like what we expect a
phone number to look like ... or not. But even that can get almost out of hand. Unless we tell the
user how to enter a phone number somewhere, it might come to us several ways, like:
(800) 555-1212
or
800.555.1212
or
800 555-1212
or others. So I'm just taking it on faith that the user has enough common sense to enter phone
numbers in some fashion that is acceptable and understandable to others that may look at the
information later on.
On this form nothing much happens until you click one of the two buttons at the bottom of the
form. If you click the [Cancel: ...] button, well, I just close the form and that's that. But if the
user clicks the [Save and Continue] button, then there is work to be done: we have to take the
information from this user form and put it someplace more permanent. In this case it is
going to be moved to a sheet in the workbook.
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 39
Page 40
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 41
Its FAST! Youre working with in-memory representations of those objects and there
simply isnt anything faster going on in your computer than memory accessing.
It is neat. Because you are working in memory, theres no need to actually jump around
in within Excel selecting various workbooks, worksheets and cells. Because you can get
to these directly in memory, theres no distracting (and slow) flickering of the screen as
you manipulate the data.
Ok, this one is more my project than yours theres 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
HTU
UTH
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.
P
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 wont get copied over
into WB01; delete an item thats 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.
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 42
by J.Latham
Microsoft Excel MVP 2006-??
59B
Often you dont 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. Youre probably used to seeing them as .TXT files and they can be opened and read easily
with a program such as Microsofts 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 theres 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
HTU
UT
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 youve 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.
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 43
Data Sources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 44
by J.Latham
Microsoft Excel MVP 2006-??
Somehow I've got to give you a good understanding of what's going on when you program using
references to objects rather than with the objects themselves. This method of working with the
objects in Excel such as Worksheets and cells, or even with multiple workbooks, is much faster
than working with them directly, and offers a lot more flexibility for you.
Let's try a couple of examples and hope I get the idea across.
Example 1: Telephone numbers. You're going to run errands today and you know that along the
way you need to make several phone calls. You have some choices on how to 'remember' the
phone numbers you need:
You can open the phone book, look up each number and enter the information into your cell
phone contacts. You've just created a 'reference' to the numbers in the phone book.
Not wanting to take the time to punch in names and phone numbers into your cell phone contacts
list just so you can delete them later, you grab the same phone book, a sheet of paper and a pen
and write the information down on the sheet of paper. Again, you've created a reference to the
numbers you'll need.
You can drag the entire phone book with you and go through the process of looking up each
number as you need it later on. A bit cumbersome and someone back at the house might want
the phone book for some other reason anyhow.
Hopefully it's obvious that either one of the reference lists you've created will provide you easier
and faster access to the information you need than going to the phone book and looking each one
up later.
Example 2: Credit Card Info. You're on your way to apply for a loan and know that they're
going to ask for current account information such as account numbers, monthly payments and
balance. Again you have some choices:
You can gather up a big stack of most recent statements and scurry off to fill out the application
with them, or you could grab the trusty not-very-high-tech sheet of paper and pencil again and
just write down the simple facts you know you will need. Voil!, a reference to the actual data.
In Excel, your sheet of paper is the computer's memory and your pen or pencil is the Set
command.
ADVANTAGES OF USING OBJECT REFERENCES
I've already mentioned a big one: speed. Performance improves dramatically when you
reference these 'in-memory' objects than if you use more direct methods of coding to work with
them.
60B
By working with the objects in memory, you often prevent having to select different sheets and
cells on them and display the updated data - this alone is a big time saver because updating the
displayed workbook/worksheets/cells is a big time user.
You don't have to actually physically "select" an object to work with it! You may even make
reference to worksheets that are hidden and to the data on them without having to unhide it and
select it and then start selecting cells one by one or in groups on that sheet. Consider the
following code:
Programming With Excel Objects
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 45
Sub Find_X_InColumnA_OnSheet1()
Const SeekValue = "X"
Dim startTime As Date
Dim endTime As Date
ThisWorkbook.Worksheets("Sheet1").Select ' wasted time, screen flickers, and
' you won't return to where your user was
Range("A1").Select ' a little more wasted time
startTime = Now() ' for timing the test
'now we really annoy the user by 'scrolling down the worksheet in column A
Do Until IsEmpty(ActiveCell)
If Trim(UCase(ActiveCell)) = SeekValue Then
Exit Do ' we found first "X" or "x"
End If
ActiveCell.Offset(1, 0).Activate ' move to next row
Loop
endTime = Now()
MsgBox "It took " & Format(endTime - startTime, "ss") & " seconds to find X"
End Sub
It's difficult to see the difference in performance of that method than with others without data to
test with. So you can use the Project03_ObjectReferenceBenefits.xls file to get some test data
into a workbook and run the above code (already in that workbook), along with the variations of
it I'm about to present to you to actually see the differences in performance. But if you want to
tough it out on your own, I'll provide all of the code here and you can copy and paste into your
own workbook, just make sure that there's a "Sheet1" in it.
As usual, the file is available by clicking the appropriate link (right-click and choose Save Target
As) on this page:
http://www.jlathamsite.com/LearningPage.htm
HTU
UT
Page 46
by J.Latham
Microsoft Excel MVP 2006-??
Sub FillSheet1()
Dim LC As Integer
Dim IL As Integer
Dim myTestSheet As Worksheet
Dim baseCell As Range
Dim rowOffset As Long
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).
Page 47
Page 48
Page 49
Page 50
Page 51
by J.Latham
Microsoft Excel MVP 2006-??
DEFINING A NAME
63B
Excel gives you the ability to assign a 'meaningful name' to a cell or group of cells (each of
which is known as a range in VBA). Assigning a name is easy to do:
Step 1: choose the cell or group of cells to be named,
Step 2: enter the name for the range in the 'Name Box' and press [Enter]
Here we have chosen cell B2 on a worksheet. It's address, B2 is
shown in the Name Box.
Next simply click inside of the Name Box to get ready to assign a
name to cell B2.
Finally, type in the name 'TaxRate' and press the [Enter] key.
NOTE: you must terminate the name entry with the [Enter] key. If
you don't, then the name is not accepted by Excel as a name.
After this is done, you can now refer to the contents of cell B2 on this sheet using its TaxRate
name. For example, you could refer to it in a formula in the workbook like this:
=1.99 * TaxRate
and the cell would show the result. Assuming there is a value of 0.875 in B2/TaxRate, then the
formula would return $0.17 (also assuming the cell with the formula in it formatted to display
currency).
You can also assign a name to a range of cells to make referencing the group easier and
'maintenance free' in your formulas and other worksheet functions.
Page 52
by J.Latham
Microsoft Excel MVP 2006-??
You can manage existing names or create new ones using this dialog.
Excel 2010 gives us a more versatile tool, the Name Manager to perform these functions.
Page 53
Page 54
Normally when you use a list of entries in a group of cells as the source for Data Validation
controlled cell entry, the list must be on the same worksheet with the cell using it as its list. But
if you have given a name to a list of cells, that list can be on another sheet in the workbook. This
gives you the ability to put several lists on a worksheet that you can even keep hidden.
Page 55
by J.Latham
Microsoft Excel MVP 2006-??
In this section Ill try to present some useful routines that can be used and reused in your own
coding efforts. The sources for these range from web sites, help forums and my own
experiences. Sorry, but theyre really not organized in any specific way, just as I have come
across them in trying to gather up content for this.
SORTING A RANGE
See the VB Help topic for SORT for all the details.
64B
In setting up for a sort you need to keep in mind that you will be sorting a range of cells, and that
the various sort keys must also be ranges or references to ranges.
The setup the variables we will need (or just want) get declared first:
Setup for single field (column) sort, which will sort an area that includes A1 to F1000 on Sheet1.
Row 1 contains labels (headers) and we will sort in ascending order based on column C.
Dim myWorksheet As Worksheet
Dim theSortRange As Range
Dim theSortKey as Range
Set myWorksheet = ThisWorkbook.Worksheets(Sheet1)
Set theSortRange = myWorksheet.Range(A1:F1000)
Set theSortKey = myWorksheet.Range(C1)
theSortRange.Sort Key1:=theSortKey, Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Note: the DataOption# parameter is only valid in Excel 2003 and later versions. Leave it
off of the command if the sort will be used in an earlier version [it will still work in 2003
and later without it]
Setup for three field (column) sort, which will sort an area that includes A1 to F1000 on Sheet1
where row 1 contains labels (headers) and we will sort in ascending order based first on column
C, then on column A and finally in descending order of column F.
Dim myWorksheet As Worksheet
Dim theSortRange As Range
Dim theSortKey1 as Range
Dim theSortKey2 as Range
Dim theSortKey3 as Range
Set myWorksheet = ThisWorkbook.Worksheets(Sheet1)
Set theSortRange = myWorksheet.Range(A1:F1000)
Set theSortKey1 = myWorksheet.Range(C1)
Set theSortKey2 = myWorksheet.Range(A1)
Set theSortKey3 = myWorksheet.Range(F1)
theSortRange.Sort Key1:=theSortKey, Order1:=xlAscending, Order2:=xlAscending, _
Order3:=xlDescending, Header:=xlYes, OrderCustom:=1, OrderCustom2:=1, _
OrderCustom3:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, DataOption3:=xlSortNormal
Page 56
Page 57
Its useful when you have data on a sheet that is dynamic and that may have a different number
of rows in it at any given time.
First thing to do is to identify a column that will have some information in it in the last possible
row of data. For this example, we will assume that column A fills that need.
Identify the Last Used Row
9B
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
Page 58
Page 59
This is complicated a bit due to the fact that its a little difficult to find the reference to the
column that is the last column in the version of Excel you are using. But we can work around it
using the Columns.Count property of the sheet.
Sub LastColumnInOneRow()
'Find the last used column in a Row: row 1 in this example
Dim LastCol As Integer
With ActiveSheet
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
MsgBox LastCol
End Sub
That comes directly from Ron De Bruins site at: http://www.rondebruin.nl/last.htm which leads
me to pretty much stop providing code examples, scratching my head trying to think up code that
you might find useful. Instead, the remainder of this document consists of links to various
absolutely excellent examples of VBA for Excel coding. In some cases, such as Chip Pearsons
site, Ive copied the table of contents with links to various Excel solutions on the sites. You can
follow those links to those code solutions.
HTU
UTH
http://www.rondebruin.nl/copy2.htm
HTU
UT
Page 60
Using a TextBox or other shape from the Drawing Toolbar offers a good deal of flexibility. You
can set the font size and format and add color to the 'button'. Plus the code can reside in any
module in the workbook.
You don't even have to have the macro written in order to create the button in anticipation of
associating a macro with it later.
Select a shape from the Drawing toolbar (Excel 2003 and earlier) or from the Insert tab (Excel
2007 and later) and place it on the sheet and size it, add text to it, and format its colors. I also
recommend setting its properties to NOT move or resize with cells.
At any point after creating the 'button' you can assign a macro to run when you click it. Simply
right click near the edge of the shape and choose [Assign Macro] and then pick the macro to run
from the list presented to you. And that's all there is to it.
DOING THE IMPOSSIBLE
There are some things that simply cannot be done using Excel worksheet formulas. Hiding
either rows or columns and unhiding them again comes to mind right away. Some other things
that you can do from the keyboard such as auto-filtering and removing such a filter can't be
controlled through formulas, but they can be done using VBA code.
71B
Providing the user with a 'button' to access these features is a nice touch because it reduces the
need to use the keyboard and the 4-click sequence of
Tools --> Macro --> Macros, select a macro and click [Run] to make it all work.
The user will definitely appreciate being able to run the macro with one click, and of being sure
to use the right macro instead of clicking the wrong one in what may be a long list of macros to
choose from.
Hiding Rows
10B
While you can use Data Auto-Filter to remove rows from view, sometimes it's easier to just hide
the rows with code. You need to know what condition you want to use to choose rows to be
hidden and what column values meeting the condition can be found.
Let us say that you want to hide all rows that do not have a value entered into column R.
Perhaps a row's data represents values for quantities of a product produced on certain dates and
you want to see all products that were produced on the date contained at the start of column R.
Hiding rows with no entry in column R would clean up the list for you.
Here is the code that would do the trick for you.
Start by UNHIDING all rows! This will make sure that only the rows you mean to hide will be
hidden at the end of the process, with no left over hidden rows from other similar actions taken
on other columns:
ActiveSheet.Columns("R:R").EntireRow.Hidden = False
Actually you can pick any column! I just chose to use R since R is the column we are about to
examine for empty cells to determine whether to hide a row or not.
Page 61
I've already given away this secret because we started off our Hide Rows routine by unhiding all
rows. But we will put it in a sub by itself anyhow. Just remember that this will NOT unhide
rows that are hidden because of data filtering - they are hidden in a different manner and will not
be unhidden with this code.
You can pick any column on the sheet, since any column includes all rows. For convenience
sake, it's probably easiest to simply use column A.
Sub UnhideAllRows()
ActiveSheet.Columns("A:A").EntireRow.Hidden = False
End Sub
Page 62
by J.Latham
Microsoft Excel MVP 2006-??
An Introduction to Debugging
13B
Debugging a project can be a simple "mechanical" process, sometimes it is almost an art. In this
section I can only present a few suggestions and at least introduce you to some of the tools
available to you to help examine code, determine values during execution and hunt down and
squash bugs. We take a simple routine that is giving us problems and see how some of the tools
can help us determine what the problem is. How to fix this particular one is left as a thought
exercise for the reader: validate information before trying to use it? put in code to ignore the
error? repremand the user for entering the wrong kind of information in the first place?
THE PROBLEM EXAMPLE
We have a simple looking routine but it isn't working for us. Unfortunately the programmer
wasn't very generous with comments, and now we need to try to figure out just why it isn't
working for us.
72B
Option Explicit
Public Const intRaiseToPower = 2 ' squared
Sub SquareANumber()
Const getRow = 2
Const getCol = 1
Const putRow = 2
Const putCol = 2
Dim intMyNumber As Integer
intMyNumber = ActiveSheet.Cells(getRow, getCol)
ActiveSheet.Cells(putRow, putCol) = intMyNumber ^ intRaiseToPower
End Sub
When we try to use the Sub we get this error:
This tells us that we are trying to perform some operation that requires some specific 'Type' of
constant or variable, but what we are trying to use is not one of them and Excel could not trick
Code Snippets and Examples
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 63
What you want to do at this point is to click the [Debug] button. Excel will then automatically
open the VB Editor (VBE) and even show you the line of code that it thinks is causing the
problem. NOTE: For some problems, Excel can get confused and point to the wrong line of
code. But that's something to cover on another day.
When we click the [Debug] button, we get this display:
Excel has pointed out the line of code that it feels there is a problem with, now it is up to us to
figure out the details.
We probably need to answer 2 or 3 questions on the way to determining the exact problem:
#1 - what sheet is the "ActiveSheet". For experienced users, this is an easy question to answer,
but if it was some object set to represent a sheet that might be hidden from view or not currently
selected, we need to know which sheet we should be examining.
An important tool you'll need to help pin the problem down and come up with a fix is the
Immediate window of the VBE.
Page 64
You can do a lot in the Immediate window: examine values, determine addresses, set values and
even issue some commands to Excel itself. For now we want to find out what sheet we are
getting a value from, so we type the following into the Immediate window and press the [Enter]
key at the end of it:
? ActiveSheet.Name
The ? is a shortcut entry for "Print" or "Show me..." and is a holdover from the very early days of
the original BASIC interpreters.
The name of the ActiveSheet is revealed to us as: Sheet1. So at least now we know what sheet
to look at, but where on that sheet do we need to be looking? We know that we should be
looking at Cells(getRow, getCol). But where the heck is that? Once again, it is the Immediate
window to the rescue. We can get it to show us the address of that cell by typing:
? Cells(getRow, getCol).Address
and pressing the [Enter] key.
By the way, you can copy from the code window into the Immediate window, which can help
prevent typos from interfering with your debugging efforts.
Page 65
And there we see a problem: Cell A2 holds some text, and since we declared intMyNumber to be
type Integer, and so a text value cannot be assigned to a numerically typed variable - and there
lies the answer to why we got "Error 13: Type Mismatch" when trying to use the Sub.
Now it is up to you to determine why someone typed text into a cell you were expecting to find a
number into (or realize that you should not type text into a cell that is going to be used for some
math processing). The Debugger has done about all it can for you, what you do to prevent the
problem in the future is a decision you have to make yourself.
OTHER DEBUGGING TIPS:
Tip #1: You can quickly determine certain values right in the code window by simply moving
the mouse pointer/cursor over a constant or variable name and its value will be displayed as a
popup tip:
73B
Or you can simply hit the [F5] key which will bring up the error message again and you
can click the [End] button on it.
Code Snippets and Examples
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 66
You do that by clicking in the area to the left of the beginning of a line of code. The dark red dot
and highlighting will indicate that a breakpoint has been set. You can remove it later by clicking
the dark red dot again, or use the [Debug] option in the menu to clear them all:
Another way to achieve much the same thing is to insert the Stop statement into the code where
you want it to break into debug mode. Simply type the word Stop on a line by itself in the code just don't forget to delete it after your debugging is completed.
Once you have halted the code where you want to, you can press the [F8] button to then single
step through your code and examine values and processes along the way to the problem line of
code. When you are ready to let the code run normally again during your debug session, press
the [F5] key - or you can terminate the execution using the [Reset] button and start all over
again.
You'll notice in the last screen shot that there are several ways of controlling what pieces of code
are executed associated with the [F8] and [F9] keys. They can all help in your effort to
determine the source of a problem, or just to go through code to see how it works.
Page 67
by J.Latham
Microsoft Excel MVP 2006-??
This section provides a list of other sites that are simply filled with useful Excel and Excel VBA
help. Ive copied their table of contents pages where they are available, however, the contents of
any site may change at any time it is the Internet, after all.
You can find a more complete list of many Excel MVP websites here:
http://www.mvps.org/links.html#Excel
HTU
UT
And if you go to the top of that page, you can look through the list for websites belonging to
MVPs in many areas:
http://www.mvps.org/links.html
HTU
UT
HTU
UT
HTU
Excel 2007
T
TH
UTH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
TH
UTH
HTU
HTU
TH
UTH
HTU
HTU
TH
UTH
HTU
UTH
UTH
HTU
UTH
HTU
TH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
HTU
UTH
HTU
UTH
Page 68
by J.Latham
Microsoft Excel MVP 2006-??
T
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
TH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
UTH
HTU
UTH
HTU
HTU
TH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
TH
UTH
Delete/Hide/Disable examples
T
UTH
HTU
UTH
HTU
UTH
HTU
TH
HTU
UTH
UTH
HTU
UTH
HTU
TH
HTU
UTH
HTU
UTH
HTU
UTH
Weeknumber/Dates
T
HTU
HTU
TH
HTU
UTH
Help information
T
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
HTU
UTH
HTU
HTU
UTH
UTH
Other pages
T
TH
HTU
UTH
UTH
UTH
HTU
HTU
HTU
UTH
Page 69
by J.Latham
Microsoft Excel MVP 2006-??
UTH
HTU
HTU
UT
Page 70
78B
T76BHU
HTU
UTH
T7BHU
HTU
UTH
TML
UTH
HTU
U TH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UT
AutoFilter - Basics
AutoFilter - Filter Text in Long String
AutoFilter - Limits to Dropdown Lists
AutoFilter - Programming
AutoFilter - Protected Sheet
AutoFilter - Status Bar Record Count
AutoFilter - Sum a Filtered List
Functions
Functions -- Count cells
Functions -- IFERROR 31-Dec-08
Functions -- INDEX 23-Nov-05
Functions -- INDIRECT 11-Nov-06
Functions -- MATCH Video
Functions -- SUBTOTAL
Functions -- Sum cells
Functions -- VLOOKUP Video
UTH
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
HTU
UTH
UTH
HTU
HTU
UTH
Jun-07
UTH
HTU
HTU
29-Apr-08
UTH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
UT
HTU
UTH
HTU
UT
G-M
31-Oct-06
HTU
UTH
GetPivotData
HTU
UT
23-Jan-09
UTH
Video
UTH
HTU
updated 27-May-09
UTH
UT
HTU
Blog, Contextures
HTU
UTH
HTU
UTH
09 Video
HTU
UTH
UTH
HTU
INDEX Function
UTH
HTU
HTU
10-Feb-06
UTH
UTH
UTH
Keyboard Shortcuts
HTU
HTU
UTH
UTH
UT
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
MATCH Function
UT
HTU
UTH
17-Jul-07
HTU
UTH
UTH
UTH
Video
HTU
UT
N-O
Names -- Naming Ranges video
Names -- Naming Dynamic Ranges with a macro
UT
HTU
UTH
HTU
UTH
HTU
Combining Data
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
HTU
UTH
22-Feb-09
UTH
UTH
UTH
Page 71
by J.Latham
Microsoft Excel MVP 2006-??
UTH
HTU
HTU
HTU
UTH
22-Sep-05
UTH
UTH
HTU
HTU
UTH
UTH
HTU
HTU
UTH
HTU
UTH
videohttp://www.contextures.com/xlDataEntry0
UTH
HTU
UTH
UTH
UTH
UTH
28-Jan-06
Order Form
HTU
UTH
30-Jul-05
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
HTU
UTH
UTH
UTH
HTU
UTH
HTU
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
UTH
HTU
HTU
UTH
UTH
HTU
HTU
UTH
HTU
UTH
UTH
HTU
HTU
UTH
HTU
UTH
UTH
http://www.contextures.com/xlPivot06.html
http://www.contextures.com/xlPivot10.htmlPiv
HTU
Contextures Blog
HTU
UTH
HTU
UTH
UT
Count Cells
HTU
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
video
UTH
HTU
UTH
HTU
UTH
UTH
HTU
HTU
UTH
UTH
H
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
HTU
TU
HTU
UTH
HTU
UTH
UTH
HTU
UTH
UTH
UTH
15-
HTU
HTU
UTH
UTH
Jan-07
HTU
HTU
UTH
HTU
UTH
HTU
HTU
UTH
UTH
HTU
UT
HTU
Q-R-S
UTH
HTU
UTH
HTU
UTH
09
HTU
UTH
UTH
HTU
UTH
HTU
HTU
UTH
UTH
UTH
HTU
HTU
UTH
UTH
HTU
HTU
UTH
HTU
UTH
UTH
Page 72
by J.Latham
Microsoft Excel MVP 2006-??
Oct-06
Sample Data
Sample Workbooks updated 10-Mar-08
Sample Workbooks (Ron Coderre) updated 20-Sep-07
Sample Workbooks (Roger Govier) updated 18-May-09
HTU
UTH
UTH
HTU
UTH
UTH
HTU
HTU
UTH
UT
HTU
HTU
HTU
UTH
UTH
HTU
UTH
HTU
HTU
UTH
UTH
HTU
UTH
UTH
HTU
HTU
HTU
UTH
UTH
HTU
UTH
Shortcuts, Keyboard
UTH
HTU
HTU
UT
UTH
Sorting a List
Sorting Data -- Programming 06-Aug-06
Store, The Excel
HTU
UTH
E
HTU
UTH
HTU
UTH
HTU
UT
UTH
HTU
Subtotal
Sum cells
Sum a Filtered List
UTH
HTU
HTU
UTH
UTH
HTU
HTU
UTH
UTH
HTU
HTU
UTH
UTH
HTU
Survey Form
UTH
HTU
HTU
UTH
HTU
T-Z
UTH
Table, Excel
HTU
21-Aug-08
UTH
UTH
HTU
HTU
UTH
UTH
UTH
HTU
UTH
HTU
HTU
UTH
UTH
HTU
http://www.contextures.com/xlToolbar01.html
UTH
06
HTU
UT
http://www.contextures.com/xlfaqFun.htmlFA
HTU
UTH
UTH
HTU
Topics Index
HTU
UTH
UT
UT
UTH
HTU
UTH
HTU
HTU
UT
UTH
Filter, Advanced
Filter, AutoFilter
HTU
HTU
UTH
UTH
HTU
UTH
HTU
UTH
UT
UTH
HTU
UTH
TU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
Page 73
by J.Latham
Microsoft Excel MVP 2006-??
http://www.contextures.com/xlFunctions02.ht
mlVLOOKUP function Video
HTU
UTH
UTH
HTU
UT
Page 74
by J.Latham
Microsoft Excel MVP 2006-??
HTU
UT
UTH
A
Absolute And Relative Cell References
Activating Excel From Other Applications
HU
HU
ActiveCell, Highlighting
HU
HU
HU
HU
HU
HU
Add-Ins, Creating
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Application-Level Names
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Page 75
by J.Latham
Microsoft Excel MVP 2006-??
My Documents Folder, Finding For
The Current User
HU
HU
HU
HU
HU
HU
HU
Named Ranges
Named Range Box, Increase The
Size Of
Named Range Box, Shortcut
Keystroke
Nested Function, Exceeding Limit
NET Function Libraries
NETWORKDAYS, A Better Way
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Newsgroups, Connecting To
Newsgroups, Excel Related
Newsgroups, Hints For New
Posters
Newsgroups, Problems Posting To
Next And Previous Worksheets
Non-duplicate Random Numbers
HU
HU
HU
HU
HU
HU
HU
HU
B
Banding, Color Banding With Conditional Formatting
HU
HU
HU
HU
Objects, Declaring
Objects, Sorting Arrays Of Objects
Objects, Connected And
Disconnected
OnTime Method In VBA
On Error handling
Optimizing VBA Code
Optional Parameters To A
Function
Optional And Arbitrary XML
defined in an XSD Schema
Option Explicit
Order, Reversing Cell
Ordinal Numbers In Excel
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
C
HU
HU
HU
ParamArray parameters to a VB
Function
HU
Page 76
by J.Latham
Microsoft Excel MVP 2006-??
Parameters, Passing ByRef And
ByVal
Parameters, Optional Parameters
To A Function
Passing Parameters ByRef And
ByVal
Parent Windows, With Userforms
Passing And Returning Arrays
From Procedures
Passwords, Forgotten
PathCompactPathEx API Function
Phone Numbers, Parsing
Pictures On Command Bar Items,
Custom
Pivot Tables, An Introduction
Positioning UserForms To Cells
PowerPoint, Naming Slides And
Shapes
Preventing Duplicate Entry
HU
HU
HU
HU
HU
CellView Add-In
Centering The Screen On A Range Of Cells
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
CodeName property
Code Modules
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Page 77
by J.Latham
Microsoft Excel MVP 2006-??
Random Numbers In Excel And
VBA
Randomize The Order Of
Elements In An Array
Ranges, Converting To Column
Ranges, Referring To Cells In
Another Range
Ranking Data In List (and
associated topics)
Recursive Code, Example Of
Recursive Programming
Techniques
Recursive Code, Illustrated With
The File System Object
Recycle Bin
Recycling A File Or Folder
Recycling The Contents Of A
Folder
References, Setting To VB
Projects
References, Missing References
In A VBA Project
Registry, Functions For Working
With The Registry
RegistryWorx DLL Registry
Component
Returning Every Nth Value In A
Range
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Rounding Times
RowLiner Cell Highlighting Add In
HU
D
HU
HU
HU
HU
HU
HU
HU
Page 78
by J.Latham
Microsoft Excel MVP 2006-??
Save Copy And Zip - XLA Add-In
Save Copy And Zip - COM Add-In
Scheduling Procedures With
OnTime
Scope Of Variables And
Procedures
Screen Flicker When
Programming To The VBA Editor
Scrolling To Center A Range
Scrolling, Detecting With VBA
Self-Referencing an instance of a
class using "Me"
Selecting Current Array
Selecting Current Named Range
Selection, Saving And Returning
To Sequence
Selection, Removing Active Cell
Or Active Area
Series, Inserting Cells And Filling
A Series
Series, Finding A Series Of Cells
That Sums To A Number
Series, Testing Whether Values
Are In Correct Series Order
Series, Testing Missing And
Present Black Of Numbers
SetParent Function For
UserForms
Shading Cells
Sheet Name, Returning
Sheet Names, Returning (VBA)
Shell Command, ShellAndWait
SHIFT, CTRL, and ALT, Testing
State Of Key
Shortcut Keys
ShortenTextToChars Function
Shortcut Keys
Shuffling Order Of Elements In An
Array
Shutdown, Detecting And Acting
When Excel Shuts Down
SizeString Function
HU
HU
HU
HU
HU
UH
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
DATEDIF Function
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Page 79
by J.Latham
Microsoft Excel MVP 2006-??
VBA
Special Characters In Cells,
Displaying Hidden Characters
Special Folders, Returning Names
Of
Standard Time And Daylight
Savings Time
Startup Errors In Excel
Status Bar, Working With In VBA
Strings, Most Or Least Common In
A Range
Strings, Concatenating With
Ranges And Arrays
Strings, Counting Characters In
Strings, Finding Characters Or
Digits
Strings, Fixed Length
Strings, Testing For Fixed Length
Strings, Shortening With
PathCompactPathEx
Strings, General Formulas
SubClassing The ActiveWindow
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
E
HU
Easter, Date Of
Easter, Calculation Of Date
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Error Handling
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Page 80
by J.Latham
Microsoft Excel MVP 2006-??
HU
HU
HU
HU
HU
F
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Page 81
by J.Latham
Microsoft Excel MVP 2006-??
User Defined Functions, Returning
Arrays
Used Cells In A Range
HU
HU
HU
HU
HU
HU
HU
User-Specific Folders
UserForm Events, Suppressing
UserForms, Modifying With
Windows API Functions
UserForms, Parent And Child
Windows
UserForms, Positioning To Cells
UserForms, Showing A UserFrom
Determined At Run-time
UTC And Local Times, And
Windows Time Formats
Utilities and Add-Ins, Third Party
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
G
HU
GetInfo UDF
Getting Help From Newsgrops
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Page 82
by J.Latham
Microsoft Excel MVP 2006-??
W eekday, Counting Between
Dates
W eekday, First And Last Of Month
HU
H
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
HU
Highlighting ActiveCell
HU
HU
HU
HU
HU
HU
HU
HU
I
HU
IF Functions, Nested
Importing Text Files
Importing Text Files With More Than 64K Records
HU
HU
HU
HU
HU
HU
HU
HU
Intervals, Dates
IsFileOpen, Testing If A File Is Open
ISO Week Numbers and Excel
HU
HU
HU
HU
HU
J
HU
Julian Dates
HU
Z
K
Zero Values, Ignoring In Functions
Zip File, Saving A Workbook As A
Zip File
HU
Keyboard Shortcuts
HU
HU
Page 83
by J.Latham
Microsoft Excel MVP 2006-??
Zip File, Save As, COM Add-In
Zooming On A Range Of Cells
HU
HU
HU
L
Last And First Names, Extracting From A String
HU
Page 84
HTU
UT
Look for the two links to downloadable Formulas and the one for downloadable Code.
JON PELTIERS CHART TUTORIALS
Jon Peltier has premium quality knowledge of Excel Charting and Graphing and you would be
hard pressed to get better starting help on Charting with Excel from someplace other than
81B
http://peltiertech.com/Excel/Charts/index.html
HTU
UT
This page has many links at the top regarding how Excels (re)Calculation engine works, and
how to make it work for you:
http://www.decisionmodels.com/calcsecrets.htm
HTU
UT
This page has lots of tips and information on how to speed up the performance of your
workbooks:
http://www.decisionmodels.com/optspeedh.htm
HTU
UT
Need to find out more detail about the memory requirements or usage in your version of Excel?
Then check out this page:
http://www.decisionmodels.com/memlimits.htm
HTU
UT
http://jkp-ads.com/Download.asp
HTU
UT
Page 85
by J.Latham
Microsoft Excel MVP 2006-??
UTH
Here is the Table of Contents for his Excel Tips at the site, with some having companion files
that can be downloaded.
General
HTU
UTH
HTU
HTU
UTH
HTU
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
UTH
Formatting
Additional Excel VBA Resources
Copyright 2008 by J.L.Latham, All Rights Reserved.
Page 86
by J.Latham
Microsoft Excel MVP 2006-??
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
Formulas
HTU
UTH
HTU
HTU
UTH
HTU
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
UTH
UTH
HTU
HTU
UTH
Page 87
Creating A Megaformula
by J.Latham
Microsoft Excel MVP 2006-??
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
HTU
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
UTH
UTH
HTU
HTU
UTH
Page 88
by J.Latham
Microsoft Excel MVP 2006-??
UTH
Printing
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
HTU
UTH
HTU
UTH
UTH
HTU
UTH
HTU
HTU
UTH
UserForms
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
Page 89
UTH
HTU
UTH
HTU
UTH
HTU
UTH
VBA Functions
HTU
UTH
HTU
UTH
HTU
UTH
HTU
UTH
HTU
HTU
UTH
HTU
HTU
UTH
UTH
UTH
HTU
HTU
UTH
Page 90