Becoming a powerful VBA user can give you an edge over others, in following ways:
Spending less time manually performing tasks, which may free time to do the
things you care about the most.
Improving your career prospects by opening new and better paid job opportunities
due to your acquired VBA skills.
Becoming a trusted and admired Excel user who can contribute and help
colleagues, friends and even your family.
You may be thinking that learning about VBA is very difficult or that only "certain" types
of people can learn how to work with this tool, but it is surprisingly easy and any one
can learn VBA with a little effort..
This Course, VBA Basics, is an introduction to the basic structure and building blocks of
the VBA language. Here are some of the topics, techniques and strategies you're going
to learn about over the next several days:
1. How to create procedures which are roughly equal to (programming) and equivalent
of macros.
2. The basic structure and components of a VBA statement.
3. How to identify and refer to the elements of the Excel application you want to
manipulate.
4. How to manipulate the Excel Application and its elements.
5. How to work with cell references, expressions and operators in VBA.
6. How to work more efficiently with the data you manipulate.
7. How to make different macros work together.
8. How to pass data between macros (from one macro to another).
9. How to work with functions in VBA.
10. How to create your own custom functions.
11. How to make decisions and proceed one way (or another) depending on whether a
condition is met.
12. How to repeat a set of actions with VBA.
13. How to create macros that are executed automatically upon an event occurring.
So, get ready to start learning about VBA's basic building blocks.
Lesson #1 of VBA Basics ‒ What are macros?
A review: At a basic level, a macro is a small computer program and for beginners a
"computer program" can be defined as:
What is a procedure?
The term "procedure" refers to a set of statements that:
You write in VBA; and is executed as a unit.
In other words, these are the instructions or commands you communicate to Excel
using VBA.
Notice the similarity between the definitions of "macro" and "procedure". Therefore, in
simplified terms, you can think of the term "procedure" as referring, from a programming
perspective, to a macro.
The rest of this Lesson focuses on Sub procedures. Function procedures are discussed
in next lessons.
It is suggested that following 3 basic rules should be followed for naming procedures:
1. Objects.
2. Collections.
3. Properties.
4. Methods.
5. Parameters.
What are objects and collections?
Within VBA, you use objects to refer to something. The following are some common
examples of VBA objects:
A workbook, represented by the Workbook object.
A worksheet, represented by the Worksheet object.
In some situations, you must refer to several alike objects at the same time. For
example:
All open workbooks; or
All worksheets within a workbook.
The VBA construct that allows you to do this is known as a collection. In other words,
objects are usually grouped into collections of related objects. For example:
The collection of all open workbooks is represented by the Workbooks collection.
The collection of all worksheets within a workbook is represented by the
Worksheets collection.
You can usually (there are exceptions) distinguish an individual object from a collection
of objects because the collection contains an "s" at the end. For example:
The Workbook object vs. the Workbooks collection.
The Worksheet object vs. the Worksheets collection.
For purposes of working with VBA, collections continue to be objects.
What are properties?
Properties describe the characteristics or attributes of an object. The following are some
examples of VBA properties:
The address of a cell (the Range.Address property).
The worksheet formula within a cell (the Range.Formula property).
The height of a row of cells (the Range.Height property).
The interior color of a cell (the Interior.Color property).
The name of a worksheet (the Worksheet.Name property).
What are methods?
Methods express an action you carry out with, or on, an object. The following are some
examples of VBA methods:
Consider, for example, when you carry out a paste special action (with the
Range.PasteSpecial method). In regular Excel, the Paste Special dialog box contains
several options that allow you to specify how Excel carries out the pasting action.
When working with VBA, you specify which of these options apply by working with the
parameters of the Range.PasteSpecial method:
Paste, which determines the part of the cell range that's pasted.
Operation, which determines whether an arithmetic operation is carried out.
SkipBlanks, which determines whether blank cells are/aren't pasted.
Transpose, which determines whether rows and columns are transposed.
Regular Excel users usually think of Excel as a single monolithic structure where
objects (for ex., workbooks and worksheets) are simply a part of that structure.
In this Lesson, you learned about objects. When working with VBA, you can treat these
objects (for ex., the Workbook object or the Worksheet object) as individual elements.
In other words, as a VBA user, you break the Excel Application into different individual
objects. Each object has its own:
Properties; and
Methods.
By modifying a property; or
By calling a method.
An object.
A dot (.).
A property(describing a characteristic/attribute) or a method (expressing an
action) of the object you work with.
You learn how to set property values and work with parameters in Future Lessons.
In the next Lesson, you learn more about objects, including how to identify the object
you want to work with.
Lesson #3 of VBA Basics.
In the previous Lesson, you learned about 5 basic VBA elements, including objects.
This Lesson focuses on objects and you learn, among others:
The objects that compose the Excel Application are organized in a logical hierarchy,
known as the Excel Object Model. Within this hierarchy, objects usually (although some
don't) contain other objects.
The entire Excel Object Model is huge. However, to understand the logic behind its
basic structure, you can consider the top of the hierarchy.
The Application object, which represents the entire Excel Application, is at the
top of the hierarchy. Application contains several objects including, for
example, the Workbook object.
The Workbook object contains other objects including, for example, the
Worksheet object.
The Worksheet object contains other objects including, for example, the Range
object and the PivotTable object.
This pattern continues to unfold in a similar fashion until you encounter objects that
contain no other objects.
Objects are usually grouped into collections of related objects. When working with the
Excel Object Model (following the examples above), you can think of the following
collections:
The Workbooks collection, which represents the workbooks that are currently
open; and
The Worksheets collection, which represents all worksheets within a workbook.
Collections are essential for purposes of navigating the Excel Object Model. For
purposes of this Lesson, the following are the 2 main reasons for this:
You usually access individual objects through the collections to which they
belong to. For example, if you want to refer to a specific Worksheet object, you
usually access that individual Worksheet object through the Worksheets
collection.
In some cases, collections allow you to work with all its members at the same
time. Therefore, instead of creating separate references to each individual
object, you can work with all individual objects at once. You do this with a
single statement that, for example:
o Modifies a property of the collection; or
o Calls a method of the collection.
1. Navigate down the Excel Object Model until you reach the collection containing
the object you want to refer to.
2. Within the collection, identify the individual object you want to refer to.
To navigate the Excel Object Model (step #1), follow 3 basic rules:
1. Start at the top of the Excel Object Model, with the Application object, and start
moving down the Excel Object Model hierarchy as required.
2. As a general rule, use properties to return objects. This is because, when an
object contains another object, the container object usually has a property you
can use to access the contained object.
3. As you navigate the Excel Object Model, use dots (.) to connect the different
objects/properties (Object.PropertyThatReturnsObject).
Consider, for example, a reference to a Worksheet object, which represents a
worksheet. From a broad perspective, you can proceed roughly as follows:
1. With an index number representing the position of the object within the
collection.
2. With the object's name.
There are a few specific considerations that apply to either option. However, at a basic
level, you can usually apply the following rules:
The following references are some examples of how you apply these rules in practice:
The object references that result from the process you learn above are very clear and
complete. They're known as fully-qualified references.
Despite their precision, fully-qualified references are usually long and difficult to
read/understand. You can simplify these object references. For these purposes, you
rely on some assumptions. Because of these assumptions, you don't have to include
every single item of the Excel Object Model when creating an object reference.
For purposes of this Lesson, the main assumptions made by VBA and their
consequences are as follows:
VBA assumes you work with the Application object. Therefore, you can usually
omit the Application object qualifier.
VBA generally assumes that you work with the active object (for ex., the active
workbook, the active worksheet or the active cell). Therefore, you can
theoretically:
o Omit the Workbook object qualifier when working with the active
workbook; and
o Omit the Worksheet object qualifier when working with the active
worksheet.
The Application object qualifier is commonly omitted when creating object references.
However, the case for omitting the Workbook and Worksheet qualifiers isn't as
straightforward. There are both potential advantages and disadvantages. Therefore,
while some VBA users recommend using fully-qualified object references, other users
recommend simplifying the references as much as possible.
In the next Lesson, you learn how to manipulate objects by working with properties and
methods.
Lesson #4 of VBA Basics.
In a previous Lesson, you learned about the two possible structures of a basic VBA
statement:
Object.Property
Object.Method
You learned how to refer to an object (step #1) in a previous Lesson. In this Lesson, you
learn how to manipulate the object (step #2).
In other words, most objects (including collections) within the Excel Object Model have
a set of properties. These properties determine, among others, how the object:
Looks; and
Behaves.
Consider, for example, the Worksheet object. The following are some of its properties:
Methods are the actions you carry out with, or on, an object. In other words, most
objects (including collections) within the Excel Object Model have a set of methods.
These methods determine what you can do to, or with, the object.
Consider, for example, the Worksheet object. The following are some of its methods:
The Activate method, which makes the worksheet the active sheet.
The Copy method, which copies the worksheet.
The Delete method, which deletes the worksheet.
The Move method, which moves the worksheet to another location.
Properties whose value you can both read and write are known as read-write properties.
Some properties, however, only allow you to read (but not write) its value. These are
known as read-only properties.
You can usually do the following 2 things when working with methods:
Some properties and methods work with parameters or values. You can use these
parameters or values to, among others:
Parameters may be required or optional. If you omit an optional parameter, VBA uses
its default value.
In previous Lessons, you learned that there are 2 basic statement structures:
Object.Property
Object.Method
You also learned that this basic structure changes when you:
In such cases, the statement syntax varies depending on whether you're working with a
property or a method.
What is the structure of a VBA statement that works with method parameters?
The basic structure of a VBA statement that works with method parameters is:
Object.Method ParameterList
The parameter list (ParameterList) is located after the method and is separated
from the method by a single space.
Individual parameters (within ParameterList) are separated between themselves
by a comma and a space (, ).
Each parameter within ParameterList has its own name. When specifying
ParameterList, you can work with named or unnamed parameters. In other words,
subject to certain rules, you can choose to include or omit a parameter's name from
ParameterList.
When working with named parameters, use a colon and an equal sign (:=) to separate a
parameter's name from its value. In other words, the structure of a VBA statement that
works with several named method parameters is:
Object.Method Parameter1Name:=Parameter1Value,
Parameter2Name:=Parameter2Value, ..., Parameter#Name:=Parameter#Value
Earlier in this Lesson, you learned that you can use methods to create a new object or
return a value. In these cases, wrap the parameter list within parentheses (instead of
using a space to separate the method and the parameter list). This results in the
following statement structure:
Object.Method(Parameter1Name:=Parameter1Value,
Parameter2Name:=Parameter2Value, ..., Parameter#Name:=Parameter#Value)
What is the structure of a VBA statement that works with property parameters?
The basic structure of a VBA statement that works with property parameters is:
Object.Property(ParameterList)
The parameter list (ParameterList) is located after the property and is wrapped
within parentheses.
Individual parameters (within ParameterList) are separated between themselves
by a comma and a space (, ).
In other words, the structure of a VBA statement that works with several property
parameters is:
Object.Property(Parameter1Value, Parameter2Value, ..., Parameter#Value)
What is the structure of a VBA statement that specifies a new property value?
The basic structure of a VBA statement that specifies (writes) the value of a property is:
Object.Property = NewPropertyValue
In the next Lesson, you learn how to work with cell references in VBA.
Lesson #5 of VBA Basics.
When working with Excel, you usually refer to rows and columns as follows:
This cell-referencing style is known as A1, after the cell in the upper-left corner of a
worksheet (cell A1).
There's, however, a second way to refer to cells in Excel. In this second cell-referencing
style, both rows and columns are identified with numbers. In other words:
This cell-referencing style is known as R1C1, after the cell in the upper-left corner of a
worksheet (cell R1C1).
There are several reasons for learning how to work with R1C1-style references. One of
the main reasons is the fact that, when working with VBA, R1C1-style references tend
to be flexible, efficient, and easier to work with.
The following are the basic rules to consider when you create cell references with the
R1C1-style:
The letter "R" stands for "row", while the letter "C" stands for "column".
The letters R and C are generally followed by a number (R#C#), where:
o The number following the letter R represents the row number; and
o The number following the letter C represents the column number.
The R1C1-style references you create by following the rules above are absolute.
How do you refer to the current cell, row or column using R1C1-style references?
If you omit the number after the letters R or C, you're referring to the same row or
column as the cell containing the reference. Therefore:
The following are the basic rules to consider when you create relative R1C1-style
references:
The numbers you specify after the letters R and C are row or column offsets from
the base cell. In other words, those numbers specify the number of rows or
columns you move away from the base cell. More specifically:
o When you specify the row offset (number following letter R):
Positive numbers move down the worksheet; and
Negative numbers move up the worksheet.
o When you specify the column offset (number following letter C):
Positive numbers move to the right of the worksheet; and
Negative numbers move to the left of the worksheet.
You wrap the numbers of the row and column offsets in square brackets ([#]).
In the next Lesson, you learn how to work with expressions and operators in VBA.
Lesson #6 of VBA Basics.
When working with VBA, you have a significant degree of flexibility in specifying what
happens to the data the expression returns.
Operators are one of the elements you can use when creating expressions. Operators
are, basically, symbols that allow you to work with the other components of the
expression.
For purposes of this Lesson, you can classify VBA operators in 5 categories:
1. Arithmetic operators.
2. Comparison operators.
3. Logical operators.
4. Concatenation operators.
5. Assignment operators.
Arithmetic operators
Use arithmetic operators to carry out mathematical calculations. The following are VBA
arithmetic operators:
Comparison operators
Use comparison operators to carry out comparisons. The following are VBA comparison
operators:
Logical operators
Use logical operators to build logical expressions. The following are VBA logical
operators:
Concatenation operators
Use concatenation operators to join strings together to create a new string. The
following are VBA concatenation operators:
&.
+.
Assignment operator
In the next Lesson, as I mention above, you learn how to work with variables.
Welcome to Lesson #7 of VBA Basics.
An object. The most common object in which data resides is a Range object,
which represents a cell range. This is what usually occurs when you're working
with Excel and your data is stored in the cells of your workbook's worksheets.
A variable.
A variable is a named storage location in your computer's memory. When you declare a
variable:
You can specify the variable name and the type of data to be stored.
VBA allocates some memory and that storage location is reserved for storing a
piece of data for as long as specified.
Once you create a variable, you can refer to (and manipulate) the stored data by using
the specified variable name.
At a basic level, VBA works with data. VBA can identify the data type of a variable in the
following 2 ways:
You can explicitly declare the data type of the variable. You do this in the
statement where you explicitly declare the variable.
If you don't explicitly declare the data type, VBA can automatically identify the
data type.
You explicitly declare a variable (and its data type) with a statement, prior to using the
variable for the first time, that does the following:
Declares the variable;
Assigns a name to the variable; and
Declares the data type of the variable.
What are the main data types you can work with?
From a broad perspective, you can group the main VBA data types in the following 6
categories:
1. Variant data type: Allows you to store almost any kind of data.
2. String data type: Allows you to store text.
3. Numeric data types: Allow you to store numbers.
4. Date data type: Allows you to store dates and times.
5. Boolean data type: Allows you to store Boolean values (True and False).
6. Object data types: Allow you to store object references and result in object
variables.
Variant is the default data type. In other words, if you don't explicitly declare the data
type of a variable, it defaults to Variant.
Variant variables can hold almost any kind of data. The exception to this general rule
are fixed-length strings.
When working with characters, Variant variables can hold between 0 and approximately
2 billion characters.
The main advantage of Variant variables is the wide variety of data types they can
handle. Additionally, there are cases in which working with the Variant data type is
recommended or even necessary. However, from a memory-management perspective,
Variant is one of the less efficient data types.
Use the String data type to hold textual data. Strings are generally quite flexible and can
contain, among others:
Letters;
Numbers;
Punctuation characters; and
Other special characters.
Variable-length strings:
o Their maximum length can change and is managed by VBA.
o They can hold between 0 and approximately 2 billion characters.
Fixed-length strings:
o Their length is set by you and doesn't change.
o They can hold between 1 and approximately 64,000 characters.
Use an asterisk (*) to specify the number of characters that the string can hold.
The number of characters is counted from left to right.
o If the assigned data is longer than the fixed length, VBA truncates the
data.
o If the assigned data is shorter than the fixed length, VBA pads the
data with trailing spaces.
There are different numeric data types. Each of the individual data types has its own
characteristics.
The following are the main numeric data types and the values they can hold:
Byte: Integers between 0 and 255.
Integer: Integers between -32,768 and 32,767.
Long: Integers between -2,147,483,648 and 2,147,483,647.
Single: Floating-point numbers within the following ranges:
o Negative values: -3.402823E38 to -1.401298E-45.
o Positive values: 1.401298E-45 to 3.402823E38.
Double: Floating-point numbers within the following ranges:
o Negative values: -1.79769313486231E308 to -4.94065645841247E-
324.
o Positive values: 4.94065645841247E-324 to
1.79769313486232E308.
Currency: Fixed-point numbers between -922,337,203,685,477.5808 and
922,337,203,685,477.5807.
Decimal (a subtype of the Variant data type): Integers scaled by a variable power
of 10, resulting in the following ranges:
o With no decimals: +/-79,228,162,514,264,337,593,543,950,335.
o With 28 decimal places:
Largest values are +/-7.9228162514264337593543950335.
Smallest non-zero values are +/-
0.0000000000000000000000000001.
Use the Boolean data type to hold the binary logical values:
True; and
False.
To assign data to a variable, use an assignment statement with the following structure:
VariableName = AssignedExpression
For these purposes, "AssignedExpression" is the expression whose result you assign to
the variable.
"Variable scope" refers to the part(s) of a VBA Project (the modules or procedures) in
which you can use a variable.
"Variable lifetime" refers to how long a variable exists before it's removed from your
computer's memory. In other words, the lifetime of a variable is the time during which
the variable's value is held by the computer in memory.
The default scope of a variable is the procedure in which it's declared. In other words,
by default, you can use a variable within the procedure in which you declare it, but not in
other procedures
The default lifetime of a variable is equal to the time in which the procedure it's declared
is running. In other words, by default, a variable is alive while the procedure in which
you declare it is being executed.
What can you do when the default scope or lifetime of a variable isn't
appropriate?
There are cases in which the default scope or lifetime isn't appropriate to achieve your
objectives. In these cases, you can declare variables that have a wider scope or a
longer lifetime.
Additionally, when working with procedure-level variables, you can work with static
variables. Static variables have a longer lifetime than regular procedure-level variables
and aren't reset when the procedure ends.
In the next Lesson, you learn how to work with a very powerful type of variable: Object
variables.
Lesson #8 of VBA Basics.
Object variables share several similarities with regular variables. You learned how to
work with regular variables in the previous Lesson.
For purposes of this Course, the main difference is the data that's stored and
represented by the variable. You use object variables to:
The main difference between declaring a regular variable and declaring an object
variable is on the data type (item #3). When declaring an object variable, you specify
the data type as Object or, even better, as the class of the object represented by the
object variable (for ex., Workbook, Worksheet or Range).
To assign data to an object variable, use an assignment statement with the following
structure:
Set ObjectVariableName = AssignedExpression
The structure of the assignment statement you use when working with an object
variable is similar to that of the assignment statement you use when working with a
regular variable. The main difference between the statement that assigns data to an
object variable and the statement that assigns data to a regular variable is the Set
keyword.
In the next Lesson, you learn how to make procedures work together by calling, and
passing data to, each other.
Lesson #9 of VBA Basics.
You can execute a procedure from another procedure. This is known as calling.
The term "procedure scope" refers to the procedures that can call a specific procedure.
In other words, procedure scope determines the procedure(s) you can call at any given
point.
You can specify a Sub procedure's scope by adding the appropriate keyword in the
opening statement, prior to the Sub keyword.
Procedures can be Public or Private. The following are the main rules and
characteristics of each scope:
Public:
o It's the default procedure scope. The associated keyword, which you
can optionally place in the opening statement, is Public.
o Public procedures can generally be called by any procedure.
Private:
o The associated keyword, which you must place in the opening
statement, is Private.
o Private procedures can be called by procedures in its same module.
In some cases, procedures may have to pass data to other procedures. Data may flow
from:
Arguments allow you to pass data to a procedure. The procedure that receives the
arguments can use that data when executed. Therefore, the final result of executing the
procedure is influenced by the arguments it receives.
What procedures can pass or receive arguments?
When data flows from the caller procedure to the called procedure, both procedures can
be Sub or Function procedures.
When data flows from the called procedure back to the caller procedure, the called
procedure must be a Function procedure. You learn how to work with Function
procedures in a future Lesson.
In a previous Lesson, you learned that the basic structure of a Sub procedure
declaration statement is as follows:
Sub ProcedureName()
The empty parentheses mean that the procedure takes no arguments. To declare a
procedure that receives arguments, include the argument list within these parentheses.
In other words, the basic structure of the declaration statement becomes:
Sub ProcedureName(ArgumentList)
If the procedure receives several arguments, you separate them with a comma and a
space (, ). Therefore, the basic structure of a Sub procedure declaration statement
becomes:
Sub ProcedureName(Argument1, Argument2, ..., Argument#)
Additionally, you can declare the data type of an argument by using the same syntax
you use when declaring the data type of a variable. In this case, the basic structure of a
Sub procedure declaration statement becomes:
Sub ProcedureName(Argument1 As DataType, Argument2 As DataType, ...,
Argument# As DataType)
Procedures can have both required and optional arguments. Specify an optional
argument with the Optional keyword.
Optional goes before the name of the first optional argument; and
All the arguments to the right of Optional are optional.
To specify a default value which VBA can use if the optional argument isn't provided,
use the assignment operator (=).
The assignment operator goes after the argument's name and data type; and
The default value goes after the assignment operator.
1. By entering the procedure name and its arguments. When you use this
structure, the arguments:
o Aren't within parentheses; and
o Are separated by a comma and a space (, ).
2. By working with the Call keyword. Call is followed by the procedure name and
its arguments. When you use this structure, the arguments:
o Are within parentheses; and
o Are separated by a comma and a space (, ).
3. By working with the Application.Run method. When you use this structure:
o The first parameter of the Run method is the procedure name; and
o The following parameters of the Run method are the arguments.
Working with procedure arguments is like working with variables. You learned how to
work with variables in a previous Lesson.
Therefore, within a procedure that receives arguments, you can generally manipulate
arguments by following the same rules you follow when working with variables.
In the next Lesson, you learn how to work with functions and create custom functions in
VBA.
When working with VBA, you can use the following 3 types of functions:
Use a VBA built-in function by calling it. In other words, the statement structure you use
to call a VBA built-in function is substantially similar to the statement structure you use
to call a procedure. You learned how to call procedures in a previous Lesson.
The arguments of VBA built-in functions have names. Therefore, similar to method
parameters (which you learned about in a previous Lesson), you can work with named
or unnamed arguments when calling a VBA built-in function.
When working with named arguments, use a colon and an equal sign (:=) to separate
an argument's name from its value.
The worksheet functions you can use in VBA are methods of the WorksheetFunction
object. The WorksheetFunction object is contained within the Application object.
Therefore, the statement you use to call a worksheet function usually begins as follows:
Application.WorksheetFunction
Function procedures, commonly known as User-Defined Functions (or UDFs), are one
of the 2 types of procedures you can create in VBA. You learned how to work with the
other type of procedure you can create (Sub procedures) in previous Lessons.
The main difference between Sub and Function procedures is what they do:
UDFs are more complex and powerful than the other functions you learn about in this
Lesson (VBA built-in functions and worksheet functions). UDFs go a step further and
allow you to create your own custom functions.
How do you create UDFs?
Function and Sub procedures share several characteristics. Therefore, several of the
rules you learned in previous Lessons apply to both Sub and Functions procedures.
At a basic level, UDFs and Sub procedures are composed of the same 3 main
elements.
1. A declaration statement;
2. A set of VBA statements; and
3. A closing statement.
The main difference between a UDF and a Sub procedure is the keywords you use in
the opening and closing statement. More precisely, when creating a UDF, you use:
The following are 2 other important structural differences between a basic Sub
procedure and a basic UDF:
1. When creating a UDF, you must always assign a value to the name of the UDF
(at least once). This is because the name of the UDF is also the name of a
variable. The value returned by the UDF is the last value you assign to the
variable (that has the UDF's name) within the UDF.
2. You can declare the data type of the value returned by the UDF. You do this in
the opening statement of the UDF, after the parentheses containing the
argument list. In this case, the basic structure of the a UDF declaration
statement becomes "Function UDFName () As DataType".
In addition to the above, you should generally store UDFs within a standard module.
By default, UDF recalculation follows the rules that apply to regular built-in functions.
Therefore, they usually recalculate when their arguments change.
Volatile functions are recalculated whenever a cell changes, even if this change doesn't
result in a change to one of the function's arguments. To mark a UDF as volatile, set the
Volatile parameter of the Application.Volatile method to True (its default value) using the
following statement:
Application.Volatile
Use the CVErr VBA built-in function to convert error numbers (in VBA) to real formula
errors.
In the next Lesson, you learn how to control the execution flow of a procedure by,
among others, executing statements when a condition is met.
Lesson #11 of VBA Basics.
Basic VBA procedures are generally executed in the same way: From top to bottom.
In certain cases, you may need to create a procedure that uses a different execution
approach. This includes, for example, the following:
These possibilities are related to the topic of flow control, which is the focus of this
Lesson.
The GoTo statement allows your code to go to a specific statement. The statement to
which the GoTo statement goes must:
The GoTo statement has some applications, including error-handling. Nonetheless, this
is usually not the most appropriate way to control a procedure's execution flow.
Use the following basic statement structure when working with the GoTo statement:
GoTo Label
You can use both numeric and text labels in your procedures. You can distinguish
labels because of their specific structure:
Labels must always begin at the first character of a line of code and can't be indented.
Some of the most important flow control constructs rely on conditions and conditional
expressions.
However, in some cases, your VBA code may need to consider several conditions. In
such cases, use logical operators to combine and test multiple individual conditions.
What is the If… Then statement? How do you work with it?
If… Then is the most basic version of the If… Then… Else statement. The If… Then
statement executes a set of statements if a condition is met (returns True).
A single line; or
A block.
Create a single-line If… Then statement by using the following basic structure:
If Condition Then StatementsToExecute
Create a block If… Then statement by using the following basic structure:
If Condition Then
StatementsToExecute
End If
What is the If… Then… Else statement? How do you work with it?
The If… Then… Else statement:
A single line; or
A block.
In practice, you're more likely to work with the block version of the If… Then… Else
statement. For these purposes, use the following basic structure:
If Condition Then
StatementsToExecuteIfConditionIsTrue
Else
StatementsToExecuteIfConditionIsFalse
End If
What is the If… Then… ElseIf… Else statement? How do you work with it?
A single line; or
A block.
In practice, you're more likely to work with the block version of the If… Then… ElseIf…
Else statement. For these purposes, use the following basic structure:
If Condition1 Then
StatementsToExecuteIfCondition1IsTrue
ElseIf Condition2 Then
StatementsToExecuteIfCondition2IsTrue
...
ElseIf Condition# Then
StatementsToExecuteIfCondition#IsTrue
Else
StatementsToExecuteIfNoConditionIsTrue
End If
The Select Case statement is a useful alternative to complex If… Then… Else
statements. Select Case uses a test expression to decide which set of statements to
execute.
Additionally, you have a significant degree of flexibility when specifying Cases. You can,
for example, group several individual conditions or situations under a single Case by
working with commas (,), the To keyword or the Is keyword.
In the next Lesson, you learn how to repeat set of statements by working with loops.
Lesson #12 of VBA Basics.
"Looping" generally refers to the repetition of a set of statements several times. Each
time the set of statements is executed is known as an iteration.
VBA contains several constructs that allow you to create loops. In this Lesson, you learn
how to work with the following 7 VBA loops:
1. For... Next.
2. For Each... Next.
3. Do While.
4. Do... Loop While.
5. Do Until.
6. Do... Loop Until.
7. While... Wend.
What is the For… Next loop? How do you work with it?
The For… Next loop is the most basic and simplest VBA loop. It repeats a set of
statements a certain number of times.
The key component within this structure is the Counter, which VBA uses to keep track
of the number of loop iterations. In practice, you can usually work with a variable of the
Long data type to create this Counter.
Counter has a start (Start) and end (End) value. You have a significant degree of
flexibility when specifying Start and End. You can, for example, use any of the following:
Hard-coded values.
User-input.
Variables.
Numerical expressions.
By default, Counter increases by 1 on each iteration. You can, however, modify this by
working with the (optional) Step keyword and StepSize parameter. StepSize can be
both:
Positive; or
Negative.
If StepSize is positive:
If StepSize is negative:
What is the For Each… Next loop? How do you work with it?
The For Each… Next loop repeats a series of statements for each object in a collection.
The key component within this structure is an object variable (ObjectVariable). This is
because VBA determines whether the statements within the loop (Statements) are
executed by considering the objects within a collection (Collection).
The Do While loop executes a series of statements while a condition is met (returns
True).
What is the Do… Loop While loop? How do you work with it?
The Do Until loop executes a series of statements while a condition isn't met (returns
False).
What is the Do… Loop Until loop? How do you work with it?
What is the While… Wend loop? How do you work with it?
The While… Wend loop executes a series of statements while a condition is met
(returns True).
In the next Lesson, you learn how to create procedures that are executed automatically
when an event occurs.
At a basic level, an event is something that happens to an object while you're working
with Excel.
VBA can identify when certain events happen. By appropriately working with events,
you can automatically execute a procedure when such an event occurs. In other words,
when the event occurs, the procedure is executed.
You can only use certain events that are made available through VBA. These 100+
events cover a wide variety of situations and work with several of the most commonly-
used Excel objects.
The procedures that are executed when an event occur are known as event-handler
procedures. Event-handler procedures are always Sub procedures.
Most of the object classes where you can monitor events have their own built-in code
modules that are automatically created by the VBE. This is the case of:
Workbooks;
Worksheets; and
Chart sheets.
The corresponding modules are stored within the "Microsoft Excel Objects" folder in the
VBE's Project Explorer. Therefore, you generally:
The Excel Application and embedded charts don't have their own built-in module in the
VBE. Event-handler procedures for Application-level and embedded-chart-level events
are stored in a Class module. Therefore, handling events at this level requires some
additional upfront work.
Finally, there are 2 special non-object events (OnTime and OnKey) whose procedures
you can store in a standard module.
You can ensure that you correctly declare an event-handler procedure as follows:
1. Select the object you want to work with in the Object drop-down list (left-side
above the Code Window).
2. Select the event you want to monitor in the Procedure drop-down list (right-
side above the Code Window).
The VBE automatically creates the opening and closing statements for:
The default event of the object you select (after step #1); and
The event you select (after step #2).
The general rules about working with procedure arguments (which you learned in a
previous Lesson) continue to be applicable.
The default value of the EnableEvents property is True. This results in events being
enabled.
Learning to automate Excel with VBA doesn't have to be difficult. I strongly believe you
can easily master Excel VBA. You just need to follow the right approach and method.
If you've made it this far, I'm convinced you have the drive, discipline and motivation to
become a powerful VBA user that's able to automate Excel and, consequently, save
time for the things that matter the most to you.
Have you previously wanted to automate Excel, but never learned how to work
with VBA?
In VBA Basics, you learned about the most basic VBA constructs. It can seem
overwhelming at first to master these (and other) fundamental VBA constructs.
If you are serious about mastering VBA to automate Excel tasks, my 2-Part Course
Bundle VBA Fundamentals is tailor-made for you.
Have you ever thought that only "certain" people can master Excel VBA? Or that you'll
never be able to learn to work with VBA because you have no previous programming
experience?
Have you tried learning how to work with macros and VBA, only to feel overwhelmed
and give up?
Have you ever followed a training program about macros and VBA, only to find out that
you're not able to apply the knowledge you (supposedly) gained to automate the
process you want?
Here's what some of the amazing members of the Power Spreadsheets community
have to say about their previous learning experiences outside of Power Spreadsheets:
I am now retired (...) and have over the years wished often I had a good working
knowledge of Excel and VBA but I never had the time (...) to achieve that goal. I
would learn a little and then get frustrated when I ran [into] a roadblock especially
with the so-called "help" within Excel and VBA.
I (...) have tried to learn VBA for years. Every time I felt I was advancing I ran into a
roadblock.
For last one week, I was looking for a source where I can learn about VBA from
scratch but I didn't find any quality source. But you are really amazing. You made me
understand the basic structure of VBA language. Your lecture is very helpful and
inspiring. Thanks a lot!
- Mayank, India
I am quite familiar with Excel but there are some aspects of the macros I cannot
grasp or understand.
- Albert Z., Malta
I have learnt to use [Excel] formulas but I want to go further and learn about macros
and [VBA], however I have no knowledge of programming language.
VBA Fundamentals will arm you with the conceptual and practical knowledge you need
to:
Automate Excel;
Save time for the things that really matter to you; and
Open new career opportunities.
During the years I've spent writing and teaching about Excel VBA, I've identified the
approaches and processes that work best for effective learning purposes. VBA
Fundamentals holds your hand through all the hard parts, including:
In other words, I walk you step-by-step through the entire process of starting to work
with the most fundamental VBA constructs. You'll be supported directly by me.
The basic structure and building blocks of the VBA language; and
How powerful and useful VBA can be in helping you take the power, flexibility
and efficiency of your macros to a new level.
Maybe you've tried everything – read all the books and vague blog posts. But you still:
Unfortunately, most books and courses available in the market take approaches that
aren't suited for Excel VBA learners. You can take the long and painful route to
mastering VBA by spending hundreds or thousands of hours following ineffective
approaches or methods.
You don't have to do the same mistakes I (and thousands of others) did.
Over the last few years, I've helped hundreds of thousands of people work with VBA.
Thousands of people have signed up for my Training, while thousands of others read
my Tutorials every day.
I've also worked with Excel VBA for years, automating a wide variety of processes.
These experiences have allowed me to identify the approaches and processes that
work best for purposes of learning how to automate Excel with VBA.
I know what it takes to take you from a complete beginner with absolutely no knowledge
about macros and VBA to a confident Power User who's able to create powerful VBA
Applications.
It took me years, and thousands of hours, to learn Excel VBA. I've drawn from my
experiences, and the experiences of thousands of Excel VBA learners just like you, to
create the VBA Fundamentals Course Bundle.
Therefore, in VBA Fundamentals, I make sure you learn in a structured and practical
way, without getting overwhelmed. I focus on making Excel VBA easy to learn for you!
In these Courses, I don't overwhelm you by teaching you advanced topics too fast.
Rather, I help you build a solid knowledge foundation that serves you in both the short
and long term. This allows you to start benefiting from the power of Excel VBA in only a
few hours. At the same time, this solid knowledge foundation allows you to confidently
tackle even more advanced topics in the future.
In other words, VBA Fundamentals gives you insight into the techniques and strategies
that truly work to create simple (but powerful) Excel macros that work as you expect.
I walk you step-by-step through the entire process. With high-quality videos and
examples along the way, you'll be able to start:
I limit access to the Power Spreadsheets Academy to ensure that I can provide the best
experience and support to enrolled students. I do, however, open enrollment to VBA
Fundamentals for the students of VBA Basics.
Therefore, the next time I open enrollment, I'll send you a time-sensitive email with all
the details regarding this opportunity to continue your path to becoming a more powerful
and efficient Excel VBA user. So look out for my emails and make sure you don't miss
any.
Even my regular emails will contain tips, tricks and strategies that will help you improve
your Excel and VBA skills.
I hope that you've gotten immense value out of this Free Email Course.
Debunk certain VBA myths (for ex., that only "certain" people can work with
VBA);
Stop bad VBA learning advice; and
Show you that mastering VBA and automating Excel with VBA is possible.
You're now smarter and better equipped than 90% of the other Excel users trying to
automate Excel with VBA – and I hope you use that to your advantage. Your
colleagues, superiors, friends and family are waiting to be impressed by your Excel VBA
skills.
I know you can do this! Congratulations again for completing VBA Basics!
Sincerely,