0% found this document useful (0 votes)
211 views158 pages

Excel VBA - 3 Books in 1

Uploaded by

Lincoln Caine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
211 views158 pages

Excel VBA - 3 Books in 1

Uploaded by

Lincoln Caine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 158

Excel VBA

2
Copyright 2018 by ___Daniel Jones___- All rights reserved.
This document is geared towards providing exact and reliable information in regards to the topic and
issue covered. The publication is sold on the idea that the publisher is not required to render an
accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or
professional, a practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document by either electronic
means or in printed format. Recording of this publication is strictly prohibited, and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained
within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any
legal responsibility or blame be held against the publisher for any reparation, damages, or monetary
loss due to the information herein, either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely and is universal as so. The
presentation of the information is without a contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are the owned by the owners themselves, not affiliated with this
document.

3
TABLE OF CONTENTS
Excel VBA
A Comprehensive Beginner’s Guide to Learn
and Understand Excel Visual Basic Applications
Introduction
Chapter 1: What You Need to Get Started
The Terminology
Understanding the Developer Window
Chapter 2: The Basics
Variable Basics
Dim VariableName As DataType
Understanding Variables
Chapter 3: Recording Your First Macro
To Change Security Settings
Assigning a Macro
Relative References
Your First VBA Program
The Insert Form Button
Chapter 4: Understanding Arrays, Operators, and Subroutines
The Two Dimensional Array (multidimensional arrays)
Operator Basics
Understanding Subroutines and Functions
Chapter 5: Decision Making Programming
Conditional Operators
Logical Operators
Chapter 6: Looping
For…Next Loops
Start To End
Step
Statements

4
The For Each…Next Loop
Do While and Do Until Loops
Do While and Do Until Syntax #1
Do While and Do Until Syntax #2
While…Wend Loops
The Exit Statement and Nesting
Nesting
Conclusion

Excel VBA
Tips and Tricks to Learn and Understand Excel VBA
for Business Analysis
Introduction
Chapter 1: Visual Basic Applications - The Basics
Let’s Get Started
A Word About Macros
Understanding Variables
Numeric Data Types
Understanding Statements
Looping
Chapter 2: String Manipulation
Chapter 3: How to Avoid Common Mistakes in Excel VBA
Overusing .Select and .Activate
Overuse of the variant type
Underuse of the Application.ScreenUpdating = False
Adding a name of a worksheet to a string when it is not necessary
Failing to qualify range references
Sub functions that are too long
Chapter 4: Learning to Debug Your Program
Compile Errors
Fixing Functional or Logical Errors
Basic Problem Solving Tips

5
Use your immediate window to find any strings that have already been
evaluated
Use data tips
Option Explicit Function
Conclusion

Excel VBA
Simple, Effective, and Advanced Strategies
to Execute Excel VBA and Its Functions
Introduction
Chapter 1: The Basic Structure of VBA
How to Create a Procedure
What to do When You Have Errors
Chapter 2: The VBA Trinity
How to Use Your Worksheet
Working With Ranges
Using Rows and Columns as Ranges
Chapter 3: Understanding the Equals Symbol, With, and Cell Functions
The Equals Symbol and What Does it Really Mean
Reading Code From a Cell
Making Use of the Cells Property
How to Copy and Paste Cells
Using the VBA Method to Create a Range.Copy
Using the Range.PasteSpecial Method
When You Want to Copy and Paste Links
Chapter 4: Using Variables Rather Than Cells
Chapter 5: Beyond the Basics
Conclusion

6
Excel VBA

A Comprehensive Beginner’s Guide to Learn


and Understand Excel Visual Basic
Applications

7
Introduction
Congratulations on purchasing Excel VBA: A Comprehensive Beginner’s
Guide to Learn and Understand Excel Visual Basic Applications and thank
you for doing so.
If you’re interested in learning VBA for Microsoft Excel, you’re probably
thinking that it is a huge undertaking, especially if you’ve never done any
type of computer programming before. Few people would deny that
Microsoft Word has some amazing software that has been instrumental in
practically every business office around the world, allowing them to do
amazing things that would otherwise have taken hundreds of hours of
manpower to do. But even with that knowledge, many may come to conclude
that unless their business needs fall into the realm of accounting or financial
analysis that their use of Excel VBA is not necessary.
Part of this belief stems from the fact that few people truly understand what
Excel VBA actually is. VBA or Visual Basic Applications, a programming
language from Microsoft that has been specifically designed for Microsoft
Excel. The only difference is that this language is embedded in the Microsoft
Office applications rather than as a separate code language on its own.
Now, some of you are probably thinking that this is already over your head.
The words programming language does not need to start a panic. VBA is
actually very easy to use so there is no need to think you must return to
school to master a series of advanced mathematic subjects or some
specialized skills in order to use it. In fact, there is a very good chance that
you are already equipped with everything you need to get started because
every function you perform in VBA can be completed within the Microsoft
Excel program. So, If you have already recorded data within the Macro
program then you already have a little experience in doing Excel VBA.
If you are familiar with Microsoft Excel then you might be wondering what
benefit would it be to learn VBA. Excel is already a program that is very easy
to use, flexible, and offers a host of new applications. But VBA can expand
your skills in Excel even further than you might have ever imagined. Think
of it as a means of learning an entirely new skill that goes above and beyond
what knowing Excel can do. This is something that can be applied in a
hundred different ways without having to put in that much more effort.

8
To get started, all you need is a Microsoft 2007 or later. This is about it.
There is no need for any additional computer programming knowledge, or
any other expertise. You will however, need to have a fundamental
understanding of how Excel works. This is all basic information that you may
be called upon to use as you go through the lessons in this book. You will
need to know how to reference a cell or a column, or how to write a simple
Excel formula. For example, how to get the program to add the quantities of
two cells or to come up with the sum of a particular row. Other than that, you
are ready to go. If you don’t already know these things, no worries. We’ll
show you exactly what you need step-by-step in order to get this basic
information as we go.
In this book, we will show you
1. How to get started
2. Fundamentals of writing your first VBA program
3. You’ll learn the basic programming techniques most commonly
used in VBA
4. We’ll look at some basic examples of how to apply VBA to your
regular Excel programming
5. Finally, we will give you some practice examples to use as you
move through each lesson.
Once you’ve gone through these basic fundamentals, you may wish to
expand your knowledge and move on to more advanced lessons on VBA
applications. We hope you’re excited about it and we look forward to taking
this journey with you. By the time you’re finished, you’ll find yourself
capable of mastering a whole new field of expertise, something that is truly
exciting and fun. If you’re ready, then let’s get started.
There are plenty of books on this subject on the market, thanks again for
choosing this one! Every effort was made to ensure it is full of as much
useful information as possible, please enjoy!

9
Chapter 1

10
What You Need to Get Started

You would be amazed to learn all of the things you can do with just a basic
Excel program. Even if you decide you only want to use the simplest of
formulas you can go a long way in creating impressive charts, documents,
and spreadsheets. However, there will inevitably come a time when you will
want to expand your knowledge and learn how to get even more out of your
Excel program. You’ll want to move beyond the basic role of storing data
and using Excel as nothing more than a glorified calculator.
The primary purpose of the VBA is to automate many of the regular tasks
that Excel already does. VBA is an extension of Visual Basic 6, one of the
most used programming languages in the world. At least until it was pushed
out by Microsoft’s .NET program along with all of the programming
languages associated with it.

The Terminology
Before we get started, it is important that you understand the different
terminology used with Excel VBA. It will help you to learn these terms first
so that once you begin, you won’t need to continuously refer back to a
glossary for an explanation as we go through it.
VBA: Visual Basic Application, a computer programming language that
allows you to create specific user-defined functions that will automate
specific computer processes and calculations.
Macro/Code: A series of actions that allow a program to process automated
functions
Objects: The objects are the different parts that a program is built on. These
could include a row, a column, a range, workbook, worksheet, etc.
Collections: A group of the same type of objects.
Object Properties: The unique properties for each object. This could include
the background, range, or any other feature related to that property.
Method: A part of the VB editor that stores code lines.
Absolute Macro: A Macro that functions on a pre-set range
Relative Macro: A Macro that operates on ranges set in accordance with a
current position on a worksheet.

11
Routine: A sequence of actions set to perform.
Variable: A memory “stack” created to store temporary values during the
time the code is running.
In addition to the above terminology, you will need to have Microsoft Excel
2007 version or later already installed on your computer. While some of the
same functions we discuss in this book can be done with older versions, the
user interface will be significantly different so the instructions we include
here might be confusing. The newer versions now display “ribbons” rather
than toolbars. These new versions are referred to as “ribbon” versions where
the various actions performed in relation to macro and writing code will
appear in the “Developer” tab.
Because of the many differences, one of the first things you’ll have to do is to
even the playing field. For example, the menu bar on the MS Excel 2010 has
an interactive rubble that allows you to control every function whereas the
older versions do not. This can make finding the controls you need for
performing certain functions difficult and confusing. The good news is that
the Visual Basic Editor (VBE) is relatively unchanged. If any of the controls
we mention in this book are difficult to find, then you’ll have to start setting
up your Developer Tab to launch the VBA project window.
However, this tab is not easily found. When you first open up Microsoft
Excel, one of the first things you’ll notice is that there is no visible Developer
Tab on the opening screen. When you look at your ribbon, it will only give
you options for File, Home, Insert, etc., the basic functions of all Excel
programs. Here are the steps to add the Developer TAB to your ribbon.
1. Right click on any part of red box inside the ribbon)
2. Select Customize the Ribbon
3. Find the Developer checkbox
4. Click OK to enable it
5. When you return to the main screen, you should be able to see
the Developer Tab in your Ribbon
Another way you can add the Developer Tab:
1. Click File
2. Under File select Options
3. Then Customize Ribbon

12
4. Then Developer
5. Click on OK
6. The Developer Tab should now appear
If you are using the Microsoft Excel 2007 version:
1. Click the Windows icon to open the menu
2. Click the Excel Options Tab
3. Under Popular, click on ‘Show Developer tab in the Ribbon’
4. Then OK
5. The Developer tab should now appear in the ribbon next to the
View tab
Now you should be able to click on the Developer Tab. This will open a
window so you can use the VBA editor and record macros and many other
features.

Understanding the Developer Window


When you click on View Code in the Developer Window, it will start the
Excel VBA Editor Code Window.
You will see that the Objects Explorer Window to the left has several sheet
options to choose from. Select Sheet1 and you will see that the Book1-Sheet1
code window appears on the screen. Let’s practice using it. Add the
following statement to the code window:
Private Sub Worksheet_Activate()
MsgBox “Welcome to Excel VBA 2010”
End Sub

After you enter the statement and click on worksheet 1, a message box will
appear:
Congratulations! You have just written your first line of code in Microsoft

13
Excel VBA. Every programming language you write from now on will have
functions written in a similar way. For example, the functions:
IF, Then, Loop, Close, and Open are common among all programming
languages. It is important that you learn these basics first. Without them, you
won’t be able to fully understand how VBA works. Once you understand
how to access the code window and have mastered a few more basics, you’ll
be writing your own code in no time at all.
Code writing does not have to be difficult. If you just remember to follow a
few basic guidelines, you should be able to do it without much problem.
It is not a random function though. As with any other undertaking, it will take
proper planning and following the rules so your program will run smoothly
and efficiently. So, before you begin keep these basic guidelines in mind:
• Before you begin writing your code, make sure you have a backup
copy of the original workbook. This will allow you to recover data if
you make a mistake and lose it.
• Define your project goals before you begin. You should know the
purpose of your code and what your final result should be. This will
help you to determine how much time it will take to develop and
what resources you need,.
• Break the project down into smaller components. Some elements of the
code will have to be developed separately before you string the entire
code together.
• Make sure you test the code before implementing. There is no such
thing as a perfect code written at a single time. Be prepared to test
and retest, looking for errors that could cause problems for your
project.
• Keep a running log of notations as you work through your code. This
is important if you have to go back later and revise it. If you have
notes, you will be better prepared to figure things out later.
• Keep a record of your code commands. If you’re not sure, record it and
then review the recordings later.
• Learn relevant commands
• Let the VBA help you. There are many nuances in the program that
can change the results of your code. Use your F1 key on the keyboard

14
to display any explanations for any command and the options you can
apply.
• If you’re not sure about something don’t hesitate to do research.
Everything may not be easily discoverable on your computer but you
can consult forums, ask questions, and surf the web to find the
answers to your questions. It will save you a lot of time and keep you
from spinning your wheels trying to figure it out for yourself. Many
things you want to do have already been done by someone else, so it
would be much easier to find their instructions online rather than try
to master it on your own.

15
Chapter 2

16
The Basics
Variable Basics
It is essential that you understand variables when creating a code. Variables
are those elements of code that are prone to variations. They can change
based on several different factors. You can think of them like a file cabinet
where you may have standard files in the cabinet but the content will change
based on data received or used.
By following some basic guidelines, using variables despite their constant
changes need not be a problem. Just by following these basic rules, the whole
process can be done quickly and easily.
When naming variables:
• Every variable must have a name that sets it apart:
• Names cannot exceed 40 characters
• Do not use spaces
• They can have only:
• letters
• numbers
• underscore characters
• Every variable begins with a letter
• They cannot contain a period or a point
Here are a few basic examples of what might be considered an acceptable
name and what is not.

Acceptable Non-Acceptable
Names Names
My_House My.House
Book1234 1234Book
LongName_999 Father&Son
A&BGroup A_B Group

17
Also the type of data used in a variable is important. In Excel VBA this data
could be separated into two different types: numeric and non-numeric.
Numeric Data: Consists of numbers that use standard mathematical operators
to compute like addition, subtraction, multiplication, and division, etc. These
could include things like test scores, subject height, weight, attendance
figures, the value of shares, the cost of goods, bills, etc.
Non-numeric Data: This is data that cannot be manipulated mathematically.
It consists of text or strings of data, Boolean data, Dates and any content that
contains only two values (true or false). It could also include variant and
object content.
You can identify the kind of data contained in a particular variant when you
use the VarType function. To do this, input the Excel VBA code IDE and
build a subroutine like the one below:
Sub TestVarType()
MyVariable1 = “Jennie”
MsgBox VarType(MyVariable1)
MyVariable1 = 2468
MsgBox VarType(MyVariable1)
End Sub
When the macro begins, you will see an 8 displayed in the message box
indicating that it is a string. It will also display the number 2, showing it as an
integer. MyVariable1 can be called a variant data type, and Excel VBA will
be able to automatically determine exactly which type of data it is.
When you assign a name and type to your data, you are actually declaring it.
This must be done before you can actually use it in a written code. There are
several different types of declarations you can assign.
Implicit Declaration: An implicit declaration is one that is not openly
declared when you assign a value to it. An example of an implicit declaration
could be MyFirstName=“John”. In Excel VBA, it will automatically create a
variable using that name and will hold it as John.
Explicit Declaration: Because implicit declarations can often end up with
errors in the written code, you should explicitly declare the variable by using
something called a DIM statement like the one shown below.

18
Dim VariableName As DataType
You have two options here. If you need to declare two or more variables you
have the choice of inputting them in different lines or entering them all in a
single line making sure to keep the separated by commas in between each of
them.
Dim VariableName1 As DataType1, VariableName2 As DataType1,
VariableName3 As DataType, etc.
When you are using a fixed-length string, you can declare the variable by
using a statement:
Dim VariableName as Strong * n,
Defines the letter n as the total number of characters that can be included in a
string. For example:
Dim yourName as String * 10
yourName is limited to a maximum of 10 characters
There are others ways you can declare data besides using the Dim keyword.
You can use keywords to indicate the full scope of your declaration. There
are three words that can be used to do this:
Private VariableName as Datatype
Static VariableName as Datatype
Public VariableName as Datatype
A Private (or local) Variable means that you are declaring that it can only be
used in the procedure you are currently working on.
When using Static, you are declaring the variable as one that can be used
repeatedly, even when the procedure has already been completed. The
majority of variables that are created within a procedure are deleted when the
Visual Basic program completes it process. However, static keywords
maintain their use of a given variable even it has finished.
Public keywords can be used to declare a global variable. In other words, it
can be used by the entire program including all the procedures and modules.
It is important to not get the constants and the variables confused. Constants
differ because their values remain consistent and don’t change at any point
when the program is running.

19
Constant Name As Data Type = Value

Understanding Variables
A variable is an algebraic expression represented by a letter. The value of the
expression can vary based on certain factors. For example, x+y=10. In this
expression you have two separate variables, x and y. Together they can equal
10. So, if x = 5 and y = 5, the result will be 10. However, x could also equal
8, 6, or even 2 and the difference between their value and the resultant 10
would tell us the true value of y.
There are several different types of variables that can be used in Excel VBA.
Here are a few examples:

Data Type Storage Range


Space
Needed
Byte 1 byte 0 - 255

Boolean 2 bytes True or False

Integer 2 bytes -32,768 to 32,767

Long 4 bytes -2,147,483,648 - 2,147,483,647


Integer
Single 4 bytes -3.402823E38 - -1.401298#-45 for negative
Precision values/ 1.401298E-45 to 3.402823E38 for
Floating positive values
Point
Double 8 bytes -1.79769313486231E308 -
precision -4.94065645841247E-324 for negative
Floating values/4.949656841247E-324 -
Point 1.79769313486232E308 for positive values

Scaled 8 bytes -922,337,203,685,477.5808 -


Integer 922,337,203,685,477.5807
(Currency)
Decimal 14 bytes +/-79,228,162,514,264,337,593,543,950,335
without a decimal

20
point/+/-7.9228162514264337593543950335
with 28 places to the right of the decimal/
smallest non zero number is
+/-0.000000000000000000000000001

Date 8 bytes January 1, 100 to December 31, 9999

Object 4 bytes Any Object reference

String 10 bytes 0 to approximately 2 billion


(w/variable + the
length) string
length
String Length of 1 to approximately 65,400
(w/fixed string
length)
Variant 16 bytes any numeric value up to the range of a
w/numbers Double

Variant 22 bytes Same as above range for variable length


w/characters + string string
length
User defined Whatever The range of each element the same as the
using Type number range for any of the data type
is
required
by
elements

As you can see from the above table, each variable has its own ranges. Some
are larger than others and their storage capacity can also vary. In any
program, the smallest memory unit is the byte and it can range anywhere
from 0 all the way up to 255. Let’s try to put this into practice.
• Start by selecting the Insert Button on the Developer Tab
• Select the Design Mode Button
• Double click on the ActiveX Button
• You should see something like this:

21
Private Sub CommandButton1_Click()
End Sub
This is the beginning point for any written code. We are now going to
practice by writing the following code to be inserted between those lines.
Private Sub CommandButton1_Click()
Dim A As Byte
Dim B As Byte
A=1
B = Range(“B1”)
Do
Range(“A”&X) = Y
X=X + 1
Y = Y + Range(“B1”)
Loop Until Z = 101
End Sub
You’ve just given clear instructions to the program detailing the variables
that must be factored in in order to execute a function. Let’s see what each of
these lines of code actually mean.
The Private Sub CommandButton1_Click() was already the first line of the
code. It is labeled as private because it won’t be found anywhere in the
Macros Button. The CommandButton1 is simply a default assigned to the
ActiveX Button, and the Click is telling the program that the code that
follows will only be executed after you click on it. This line of code is
automatic when you are opening up a Design Mode. The additional code you
create is all you.
Dim declares what variables to use. X is the variable that ranges from 0 to
255
X=1
This adds the value of 1 for the variable
Y - Range(“B1”)
This makes the value of Y the same as the value found in cell B1

22
Do
Gives the command to perform this function
Range(“A” & X) = Y
You already know the value of X so the range AX actually means
Range(“A2”)=Y. You also know that Y is the value found in cell B1. So, if
you add 5 to cell B1, the Y = 5. Finally, the Range(“A1”) = 5.
X=X+1
This shows that X=1+1 because at that point in time X=1. After executing
this formula X = 2. Each time this function repeats, it will change based on
the variable X=X+1 again, increasing the value with each iteration.
Y = Y + Range(“B1”)
This instruction will perform the same process as before but with a new value
added to Range(“B1”). So, if we see that the B1 cell contains a 5, then it will
add another 5 to the equation and follow the sequence based on whatever data
is contained in B1.
Loop Until X = 101
This means that the process code between Do and LOOP will repeat until X =
101.
End Sub
When the program has satisfied all of the above instructions it will end the
procedure.
If you test this program out, you will find that it will adjust based on
whatever data you add to cell B1. If you add the number 1, the program will
fill up the cells one at a time; if you put a 2 into cell B1, it will add them two
at a time. But, if you put the number 3 in the cell, you will hit your first snag
as it will give you an overflow and will not be able to stop at the point where
you want it to end the program.
Snags, or bugs, are errors that pop up when you write a code that doesn’t
match all the parameters. Because in the above program, the code works only
with numbers from 0 to 255. The problem presents itself when you ask the
file to go 3 at a time. In that case, the range should be from 3 to 300, which
would be more than the 255 range. You will have to fix that problem first, for
it to work correctly.
You have two options. First, you can increase the variable or you can ask

23
Excel to add it automatically.
If you increase the variable you can change it from the byte (0-255) to integer
(-32,768 to 32,767). If you are confident that you won’t be working with
anything higher than that, then this would be your best option. You can even
change it to “long”, which has a range that goes from -2,147,483,648 to
2,147,483,647. With these options you could have a range that could easily
go into the millions. But what would you do if you had to do something
where the value in the B1 cell could be in the billions? In such a case, even
the long variable would not be sufficient. It might be best to not declare the
variable at all. Instead, Try writing the code like the example below:
Private Sub CommandButton1_Click()
Dim X As Byte
X=1
Y = Range(“B1”)
Do
Range(“A” & X) = Y
X=X+1
Y = Y + Range(“B1”)
Loop Until X = 101
End Sub
Another alternative is to declare the value as a Variant, which will allow any
number or letter to be used. It could look like this:
Private Sub CommandButton1_Click()
Dim X As Byte
Dim Y As Variant
X=1
Y = Range(“B1”)
Do
Range(“A” & X) = Y
X=X+1

24
Y = Y + Range(“B1”)
Loop Until X = 101
End Sub
There are several advantages to writing your code this way. Keep in mind
that variables stored in RAM Memory will only use 1, which is the smallest
amount of memory possible. However, when you store a variable in the
Memory it is possible for it to take up as much as 22 bytes and sometimes
even more depending on the type of variable you are using. This could cause
the program to run very slowly, even when performing the most basic of
tasks.

25
Chapter 3

26
Recording Your First Macro

Once you have a Developer Tab in place, you’ll start to see a few options that
are now available to you. One of those is the Record Macro option.
A Macro is basically an automated sequence you want to access whenever
you want to have the program automatically do certain work for you. This
can be a great tool to use if you have a specific task you must complete on a
regular basis; you can save yourself valuable time by automating that
function. When you record a Macro, the system will perform the function
without the need for a set up or a prompt from you.
It is very important that you learn to use Macros well because if you’re not
careful, they could become the source of many problems. It is not unheard of
for documents and other stored data to be accidentally deleted because of
incorrect use of a Macro. For that reason, Microsoft has decided that Macros
are not a default tool that you can easily access. However, if you master it
well, it does give you the ability to change your system’s security level so
you can record your own Macros. So, before you can record a Macro, you
will need to downgrade your computer’s security level first.

To Change Security Settings


1. Under the Developer tab, find the Code group
2. Select Macro Security
3. You will see the Trust Center page appear
4. Select the security level you want
When you look at your screen, you will see a list of options to choose from
will appear.
• The Trust Center is where you can change the security settings for any
of your office files
• The Trusted Location folder allows you to open selected files without
having to go through the security features installed in the Trust
Center. When you save files to this folder, it is important for you to
only save those that originate from a source you know is reliable.
• You can change any of the Trust Center settings

27
• If you have any Excel Program from 2010-2016
• Click FIKE on the main menu
• Click Options
• If you have Excel 2007
• Click the Window’s icon to open the menu
• Click on EXCEL Options
To add new Trust Locations
• In the Trust Center, lick on Trust Center Settings
• An Excel Options screen will appear
• Click on Add new location
• The Trust Location box will appear
• Click Browse
• Choose the desired folder
• Click OK
• Your selected folder will be added to the list of trusted locations.
To remove a Trusted Location
• In the Trust Center, select the location you want to remove
• Click on Remove
• Click OK
When saving files it is important to understand that there are several versions
of Microsoft Excel. Prior to the 2003 version of Excel, files were saved using
the extension “xls”. Later versions used the new “Ribbon” feature with the
extension “xlsx”. Any version that uses xlsx extension cannot store Macro
commands so in order to be able to save Macros in those versions, you must
save them with an “xlsm” extension.
If you attempt to save a Macro with the “xlsx” extension you will get a
warning that says:
The following features cannot be saved in macro-free workbooks
You will be prompted to click either Yes or No. If you click No, you will

28
have to choose a macro-enabled file from the list. If you choose Yes, you will
be able to save your workbook as an .xlsx file and then delete the macros in
it.
In order to save it as an xls file, click No and then save the file again.
By saving the file with the .xls extension you will be able to run Macros in
the Ribbon versions but you will be limited as to how may rows and columns
you can use. For most people that won’t be much of a problem. In the 2003
version of Excel, the maximum number of rows as 65,536 but in the Ribbon
versions, the number of rows was expanded to 1,048,576, which is more than
enough to meet the needs of most people.
To get started, your worksheet will need a command button set up in order to
assign the code lines (macros).
1. Click Insert on the Developer tab
2. Find the ActiveX Controls group and select the Command Button
3. Drag the command button to the worksheet
Now you are all set to assign your Macro.

Assigning a Macro
1. Select Design Mode
2. Right click on the CommandButton1
3. Select View Code as shown in the image
4. The VBA Editor will appear
5. Place the cursor between the Private Sub
CommandButton1_Click() and the End Sub as shown in the
image below
6. Type in the following code line: Range (“A”). Value = “Hello”
Note: you will notice that the Project Explorer can be seen on the left side of
the page with labels Sheet1, Sheet2, and Sheet3. If it does not appear, click
the View tab, then select Project Explorer. When you are ready to key in the
Code window for the first time, select the option for Sheet1.
Now, you can close the Visual Basic Editor
7. Deselect the Design Mode

29
8. Select the command button on the sheet
You’re all set. You have just created your first Macro in Excel!!!

Relative References
Directly below the Record Macro button is the Relative References button.
This is used to record more detailed macros where the process needs to be
applied to several different ranges rather than to one pre-established range. It
is a very practical function as any macro recorded without the relative
references will repeat the same process on the same cells used when the
initial recording was made. However, by using the relative references button,
the macro will run from whatever cell is active. The only thing you will need
to do is to choose the cell and run the Macro.
To use the Relative References button, simply click on it to activate. It will
become active and remain that way until you click on it again to deactivate it.
Being able to create a Macro is a fundamental skill necessary in the VBA
program. If you create a Macro without the relative references, then it is just a
matter of selecting the cell and telling the program what to do.
• Create your new Macro without relative references
• Select the A1 cell
• Write the number 1

• Press enter

30
• Stop recording.
• Look for the Visual Basic button and click on it (next to the Record
Macro button)
• A code will appear that looks like the following:
Range(“A1).Select
ActiveCell.FormulaR1C1 = “1”
Range(“A2).Select
You have just written a few directions in Visual Basic. You’ve given the
program a few orders to follow.
1. Select the A1 Cell
2. Write the number 1
3. Select the A2 Cell
The program is now able to perform the exact function you just did. Now,
rather than you having to manually do this function, you’ve given the
program a shortcut that cuts through the process much faster. You can now
edit the code further so you can expand the function to do something
different. You have set the pattern - select, write, select - you can continue
this pattern by adding a few more lines of code. It could look similar to this:
range(“A1”).Select
ActiveCell.FormulaR1C1 = “1”
Range(“A2”).Select
ActiveCell.FormulaR1C1 = “2”
Range(“A3”).Select
ActiveCell.FormulaR1C1 = “3”
Range(“A4”).Select
And so on.
When you run the Macro, you will see that you now have an alternative way
to do it. Notice the green button that sits directly above the code? Click on it
then click on the Excel symbol, which will take you to the Excel Spreadsheet.
You’ll notice that the cells A1:A3 are already filled with the data you wrote
and the Cell A4 has already been selected.

31
While this is a very effective way to write code, it can become quite
cumbersome to list every cell that needs to be filled in one by one. There is
another way to write the code that will allow you to skip the mundane details
of listing each cell separately.
Try adding the code this way:
Range(“A1”) = 1
Range(“A2”) = 2
Range(“A3”) = 3
By doing it this way, you can program Excel to skip certain steps but still
achieve the same results, speeding up the amount of time dedicated to
programming.
You can expand this even further. You can avoid listing every single cell in
the code by taking an even bigger shortcut. There are several ways to do this.
First, by adding a number 1 to the A1 cell and holding down the right click
on the small square you can scroll all the way down to the last cell you want
included in the task. When you check it in Visual Basic it will look
something like this:
Range(“A1”).Select
ActiveCell.FormulaR1C1 = “1”
Selection.AutoFill
Destination:=Range(“A1:A100”), Type:=x1FillSeries
Range(“A1:A100”).Select
This code will allow the program to fill in each cell in sequence rather than
give the same value to every cell included.
There are many different functions you can create when you record a Macro.
Whether you want to fill up your cells in sequence or you want to give a set
value to something else, many of these functions can be done simply by
recording a Macro.

Your First VBA Program


Sometimes however, there are certain functions that cannot be done by
simply recording a Macro. Perhaps you’re working on a project that can’t
simply order cells sequentially but you will be calculating real numbers and

32
solving real problems. This is where your Visual Basic Application comes in,
While this is a more advanced programming langue, you won’t need to learn
any special VBA coding or any programming language to use it. Keep in
mind though, that when you record a Macro the program will record
everything you do, including your mistakes. So, when you go back to run it,
it will do only what you tell it to do. This is why, it is more important than
ever to make sure that your programming is exactly as it should be. If you
make a mistake, you have only two options.
1. Re-record the Macro or
2. Edit the VBA code
Remember, your goal is to make your Excel more efficient so your code must
be written well. So, how can you write good VBA code if you don’t know
basic computer programming? There is one thing you should know about.
Let’s examine more closely a few things that will help.

The Insert Form Button


Now that you understand how to record a Macro you will want to find a more
efficient way of running them. This can be done by using the Insert Form
Button. This convenient feature allows you to run the Macros simply by
clicking on it.
To find the Insert Form Button, go to the Developer Tab and then choose the
Insert button. Two boxes will appear: One will be for Form Controls and the
other for ActiveX Controls. Select the Form Control Button, then hold and
drag so you can create the size of the button. When you release your hold, a
window will pop up, which will allow you to select the exact Macro you want
to run.
Keep in mind that there are certain things that a Macro can’t do. This is why
you will need to use the Insert ActiveX Button. Under the Developer Tab,
click on Insert from the pulldown menu and select ActiveX. Hold and drag to
create the button and place it in the spreadsheet. The ActiveX button is very
different from the Insert Form Button because it works directly with VBA.
The ActiveX Button will allow you to create a sequence of numbers based on
set values you can insert into a specific cell. For example, you can add a
number in the cell and the program will set up a pattern that will increase
sequence by that number. If you add the number 1, then the pattern will set
up a sequence of numbers that will increase by 1 with every entry. If the

33
number in the cell is 5 then the sequence of numbers will increase by 5 with
every entry. You can continue this throughout the program until you’ve
included it into every cell on your spreadsheet.

34
Chapter 4

35
Understanding Arrays,
Operators, and Subroutines

Whenever you work with one item in the Excel VBA program, one variable
is all that is needed. However, there will be times when you may have to
work with a list of similar items and you need to declare an array of variables
rather than just one. For example, if your task requires you to enter hundreds
of names, you could do them one at a time but you could also declare them
all contained in one array.
When you have a collection or a group of variables that all share the same
name and the same type of data, you have an array. To distinguish between
them you use something called a subscript, which is the index value of each
item. You see this when you see features like…
Studentname (1)
Studentname (2)
Studentname (3)
Studentname (n)
So, how can you use Excel VBA to declare a name?
You can utilize the DIM statement. This allows you to declare your array in
much the same way as you would when declaring a single variable. There are
several different types of arrays you can declare.
The One Dimensional Array: When declaring a one-dimensional array use
this as an example:
Dim arrayName(index) as dataType or Dim arrayName(first index to last
index) as dataType
So, for example, suppose you needed to declare an array that consisted of 10
elements.
Dim PatientName(10) as String Dim PatientName(1 to 10) as String
Dim PatientResult(10) as Single Dim PatientResult(1 to 10) as Single
In the above example, the array PatientName of five strings is shown by
using the keyword Dim. You can use an InputBox so that the user can input
data directly into the program. The For..Next loop can also be used to accept

36
the data and then give you the corresponding names it finds in Cells A1 to
E1. The code will look like this:
Private Sub Button1_Click()
Dim HospitalName(1 to 5) as String
For I = 1 to 5
HospitalName(i) = InputBox(“Enter patient Name”)
Cells(i, 1) = HospitalName(i)
Next
End Sub
Another way you can declare an array is by using Dim HospitalName(5) As
String. With this method when the program begins, you will notice the input
box, which will repeat the action for the set number of times and allow the
user to input the number of names required, which will automatically be
placed in the spreadsheet.
Some users prefer to declare multiple arrays on a single line. Look at the
example below. You will see there are three arrays declared on a single line
with a comma separating each one:
Private Sub CommandButton1_Click()
Dim PatientName(3) As String, PatientID(3) As String,
PatientResult(3) as Single
For I = 1 to 3 StudentName(i) = InputBox(“Enter student
Name”)
PatientID(i) = InputBox(“Enter patient ID”)
PatientResult(i) InputBox(“Enter patient result”)
Cells(i, 1) = PatientName(i)
Cells(i, 2) = PatientID(i)
Cells(i, 3) - PatientResult(i)
Next
End Sub
When running this program, you will see three separate input boxes

37
prompting the user to enter the patient name, patient ID, and the patient
results. The process will automatically repeat for each of the three times until
all of the relative details for the patients have been entered. Then all the data
will be shown in an output display spreadsheet.

The Two Dimensional Array (multidimensional arrays)


When you have arrays that have two or more dimensions, which are needed
when working with a more detailed and complex database. In these types of
arrays the data is usually organized in a table. For these you need to have a
multidimensional array.
In a two-dimensional array, you might see the data as a table with labeled
rows and columns. One index can be represented by the rows and another
index could indicate the columns. Here we will explain the basics of a two
dimensional array and you can expand the same theories to cover
multidimensional arrays on your own.
Whenever you need to declare a two-dimensional array, use this statement
Dim arrayName (num1, num2) as datatype
The num1 becomes the suffix of the 1st dimension of the last element and the
num2 becomes the suffix for the 2nd dimension of the last element. Start the
suffixes for the elements with (0, 0). If your Option Base is already set to 1,
then start the suffixes with (1, 1) instead:
Dim Score (3, 3) as Integer
This code allows you to create a two-dimensional array with 16 different
elements, which will be organized into a table format like this:

If you choose your Option Base to be set at 1, there will only be 9 elements
but if your first element starts with suffixes (1, 1) you can reformat the
declaration to:
Dim Score(1 to 3, 1 to 3) as Integer
Imagine that your business is looking to track the performance of its sales

38
team over a period of several days. With this formula you can create a 5x2
array using the Excel VBA by using the following VBA code:
Private Sub Button1_Click()
Dim SalesVolume(2 to 6, 2 to 3) as Single
Dim SalesPerson as Integer, Day as Integer
For SalesPerson=2 to 6
For Day=2 to 3
SalesVolume(SalesPerson, Day)=inputbox(“Enter Sales
Volume”)
Cells(SalesPerson, Day)=SalesVolume(SalesPerson, Day)
Next Day
Next SalesPerson
End Sub
When you run the program, the input box will give 10 prompts to the user to
enter the sales volume. Once all the data is entered, the values will the
calculated and inserted into the spreadsheet.
To ensure that the user puts in the right sales volume, change the line 5 state
to:
SalesVolume(SalesPerson, Day) = InputBox(“Enter Sales Volume
of” & “SalesPerson” & (SalesPerson - 1) & “Day” & (Day - 1))
This instruction is much clearer and will result in the following image
appearing:

Arrays can be a very efficient way of storing lists of multiple items that are
similar in type. As you learn and practice declaring different types of arrays,

39
you will become more adept at taking advantage of the ease of this type of
function.

Operator Basics
Being able to use operators correctly is an important part of writing VBA
program code. These operators (or symbols) are used in a wide range of
functions including computing values, performing mathematical operations,
and making comparisons. All functions that the VBA has been especially
designed for.
There are several different types of operators but they will all fall into three
different categories:
• Arithmetic
• Comparison
• Logical
Let’s look at each of these separately so you can better understand how they
work.
Arithmetic Operators: are primarily needed for mathematical operations.
Some of the symbols you will readily recognize and others may be new to
you.
^ Exponential as in MsgBox 2^4 gives a value of 16
* Multiplication
/ Division
Mod Modulus (gives you the remainder resulting from dividing an
integer)
\ Integer Division (eliminates any decimal places)
+ or & String concatenation
Comparison Operators: These are operators used to write codes that need to
make decisions.
If mark>50 then
MsgBox “Pass”
Else

40
MsgBox “Fail”
Endif
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
= Equal to
<> Not equal to
When using letters, the order is usually A>B>C>…….>Z
The result will show the returns in MsgBox A>B consistently True
Logical Operators: These write decision-making codes by making
comparisons of values or expressions.
And Logical conjunction
Or Logical disjunction
Not Logical negation
Xor Similar to Or, but the result can be False if both comparison values
are true

Understanding Subroutines and Functions


Being able to use operators correctly is an important part of writing VBA
code. These operators compute values, perform operations, do comparisons,
and a wide range of other functions that the VBA is designed for.
There are several different types of operators but they will all fall into three
different categories:
• Arithmetic
• Comparison
• Logical
Let’s look at each of these separately so you can better understand how they
work.
Arithmetic Operators: These perform different mathematical operations.

41
Some of the symbols you will readily recognize and others may be new to
you.
^ Exponential as in MsgBox 2^4 results in a value of 16
* Multiplication
/ Division
Mod Modulus (gives you the remainder from an integer division)
\ Integer Division (eliminates the decimal places)
+ or & String concatenation
Comparison Operators: These are operators used to write codes that need to
make decisions.
If mark>60 then
MsgBox “Pass”
Else
MsgBox “Fail”
Endif
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
= Equal to
<> Not equal to
When using letters, the order should be is A>B>C>D>……
This will make MsgBox A>B returns consistently true
Logical Operators: When writing decision-making codes, the following
listed operators should be used to compare the different values and
expressions to decide what the program should do.
And Logical conjunction
Or Logical disjunction

42
Not Logical negation
Xor Similar to Or, but if both comparison values are true the returns will
be false

43
Chapter 5

44
Decision Making Programming

Sometimes you will need to write a code that tells the computer to make a
decision. This part of the VBA programming makes it possible for your
computer to solve problems and return feedback to the user. To create a
decision making program, you will use the syntax If…then…Else to process
the data. It is important to remember that in order to maintain control of how
the data flows, you must use the entire statement in conjunction with both the
conditional and logical operators.

Conditional Operators
= Equal to
> Greater than
< Lesser than
>= Greater than or equal
<= Less than or equal
<> Not Equal to

Logical Operators
And Both sides must be true
Or One side or the other must be true
Xor One side or the other must be true but not both
Not Negates truth
Use the following example when applying these operators to your code.
First, you want to be sure that you select the Command Button1 on your
spreadsheet so you can open the Editor.
Select the RND function to begin generating random numbers.
Use the syntax Int(Rnd*100) to generate random integers in the 0 and 100
range.
If the mark is in the cells(1,1), use the If…Then…Else statement to enter the
relevant data in cells(2,1). This way, after you select the command button 1,

45
it will automatically enter any random within that range in cells(1,1) and the
relevant mark in cells (2,1).
The Code should look something like this:
Private Sub CommandButton1_Click()
Dim mark As Integer
Dim grade As String
Mark = Int(Rnd*100)
Cells(1, 1).Value = mark
If mark < 20 And mark >=0 Then
grade = “F”
Cells(2, 1). Value - grade
ElseIf mark < 30 And mark >= 20 Then
grade = “E”
Cells(2, 1). Value = grade
ElseIf mark < 40 And mark >= 30 Then
grade = “D”
Cells(2, 1).Value = grade
ElseIf mark < 50 And mark >= 40 Then
grade = “C-“
Cells(2, 1).Value = grade
ElseIf mark < 60 And mark >= 50 Then
grade = “C”
Cells(2, 1).Value = grade
ElseIf mark < 70 And mark >= 60 Then
grade = “C+
Cells (2, 1).Value = grade
ElseIf mark < 80 And mark >+ 70
grade = “B”
Cells(2, 1).Value = grade
ElseIf mark <= 1— Ad mark >=80 Then
grade = “A”

46
Cells(2, 1).Value = grade
End If
End Sub
The output will be shown in the spreadsheet according to the code you have
written.
Now that you have learned the If…Then…Else statement, let’s take a look at
how to write another decision making program. The Select Case…End
Select. This type of programming is used when the If…Then,. Else statement
becomes too cumbersome and difficult. Here is the basic format of the Select
Case…End Select program.
Select Case Variable
Case value 1
Statement
Case value 2
Statement
Case value 3
Statement
(repeat as many times as needed)
Case Else
End Select
Now, let’s break this down and see how it works by using a couple of
examples.
First example:
When you want the system to automatically assign a comment or a phrase in
relation to a corresponding grade you can use this example. If you look at the
previous example, if the actual grade is A, it can assign a comment like
“High distinction”. It can then make distinctions for the remainder
accordingly with A- as distinction and so on.
To start writing this type of code make sure your command button is already
on your spreadsheet and begin the Editor. Then start your code as follows:
Private Sub CommandButton1_Click()
Dim grade As String

47
Dim grade As String
grade = InputBox(“Enter the grade(A, A-, B, C, E or F”)
Select Case grade
Case “A”
MsgBox “High Distinction”Case “A-“
MsgBox “Distinction”
Case “B”
MsgBox “Credit”
Case “C”
MsgBox “Pass”
Case Else
MsgBox “Fail”
End Select
End Sub
Second example:
Here, grades can be processed based on the marks received. So, in this case, a
letter grade will be assigned based on the student's score. So, for any student
that gets an 85, the correct grade will be A but if the score is 20 the program
will assign an F. To do this, use the statement. Value1 to value2. This will
specify the value of the range that will be used in each case.
You should also input a special error case so that when any values fall
outside of the specified range it can return a result of invalid.
Here is a sample code:
Private Sub CommandButton1_Click()
Dim mark As Single
Dim grade As String
mark = InputBox(“Enter the mark”)
Select Case mark
Case 0 - 29

48
grade = “F”
Case 30 to 49
grade = “E”
Case 50 to 50
grade = “D”
Case 60 to 69
grade = “C”
Case 70 to 79
grade = “B”
Case 80 to 100
grade = “A”
Case Else
grade = “Error!”
End Select
MsgBox grade
End Sub

49
Chapter 6

50
Looping

At times, you will need to write code that allows a procedure to be repeated
over and over again before it is completed. This process is called looping and
can be very practical in many different business settings. If you’ve been
working with Excel VBA for a while, you’ll soon come to realize that
Looping is one of the most powerful structures included in the program.
Still, looping is not the easiest of functions to understand. In the simplest of
terms, looping is when a specific action is repeated within a program until the
desired result is reached. So, rather than having to rewrite code each time the
action needs to be executed, by writing looping into the code, the computer
will automatically perform the function without any special prompting from
you.
Excel VBA does only two things. First, it executes certain statements and
secondly, when all the statements have been executed, it returns to the
beginning and repeats. There are two different types of loops. A category 1
loop is a fixed-iteration loop that you can program to repeat for a set number
of times. There is also the category 2 loop, which is more flexible and can be
adapted to repeat until the desired result is achieved.
In both cases, the factor that determines how many times a statement is
executed is called the “loop invariant” or the “loop determinant.”
These can be divided up further into two different groups: Numeric
expressions, which are those that can be evaluated as numbers and Logical
expressions, which evaluate factors as either True or False.
There are actually several different ways you can write loops depending on
what you want your end result to be.
For…Next
For Each…Next
Do…
Do While and Do Until
While…Wend
While there will be times when you’ll use all of these, the most commonly
used are the For…Next and For Each…Next, which are classified as fixed

51
integration loops and the Do While and Do Until which are the most flexible
and can be adapted to different circumstances.
There is a good reason to learn to use loops when you write code. Regardless
of whether you’re writing arrays, functions, subroutines or any other event
into your code, inevitably you’ll want to repeat those actions. Looping is like
the secret weapon that can save you lots of time and energy by serving as a
Macro inside of your Macro, whenever you need it.
That alone is enough to convince you of the value of programming loops
when writing your code. But another very compelling reason to learn this
skill is that the Macro Recorder cannot record loops. So, if you are going to
use loops in your VBA code is more important than ever for you to
understand the fundamental codes behind them.

For…Next Loops
These are the most basic of all the VBA loops and is the most commonly
used. They are used when you want a particular set of statements repeated for
a pre-determined number of times. As you look at the syntax below for the
For…Next loop, notice the square brackets ([]) and how they are used.
“For counter = start To end [step step]
[statements]
[Exit For]
[statements]
Next [counter]
Now, let’s identify some of the elements of this particular looping structure.
The Counter: this is the key element for any For..Next loop. It tells the
program to repeat the statements for a specified number of times. You use the
loop counter to help you to keep track of how many times the program has
repeated the statements.
The counter uses a normal numeric variable so you can’t use a Boolean or an
array. This way, you can change its value within the loop’s block of code.
While this is not recommended (it can alter your code in such a way that it
can be more difficult to debug) it is possible to do if you find it necessary.
You should also notice that within the syntax, the [counter] is found in two
different positions. First, in the opening statement, after the keyword For.

52
This position is necessary. It is also found at the very end of the For…Next
loop after the Next keyword. This position is optional. Without it, the VBA
code is executed as a counter anyway.
However, you may find some instances where the second position could
prove more practical than to just rely on one.

Start To End
The loop counter allows your code to keep track of how many times the
statements have been executed. The start to End element allows your code to
determine at what values and variables the counter starts and stops with. The
value for starting the counter does not have to be linear, in that it does not
have to be smaller than the value for the end. You can select values using
either of the following rules.
• A start value can be smaller than the end (start,end).
• A start value can be larger than the end (start.end).
So, when deciding on the start and end values you’re not limited and can also
use variables that give you more flexibility. This way, you can choose to run
your loop backwards or forwards without being boxed in.

Step
So, now you understand that the For…Next loop must have a counter and
that you also need to determine the start and end values for the loop. The Step
is another element that allows you to determine how the loop will change
with each iteration. In short, it tells you how much the counter will change
each time it loops.
To make this point clear, imagine that you want your loop to count from one
to one hundred. Your starting value would be the number 1 and your ending
value would be number 2. If you’re counting one at a time, then the step
would be 1 and the counter would count accordingly.
1, 2, 3, 4, 5…100
However, if you change the step to 2, then the counter will change its method
and it would count to 100 by 2s.
2, 4, 6, 8, 10…100
You could also use the step to count by even or odd numbers, by fives, tens,

53
and so on.
Of course, you do not have to explicitly define a step value. If you do not, the
loop step will automatically use its default value of 1. You do have the option
of defining a value, either positive or negative for your step.

Statements
Statements are the lines of code that you want the program to repeat. There
are no limits set on the number of statements allowed in a loop.
The Exit for Statements is also optional. They are a specific type of Exit
statement that allows you to “exit” a block of code. Exit statements are used
to terminate the loop and transfers control to the statement that follows the
loop or to the keyword for the For…Next loop.
Now, let’s try to put this all together.
• Step 1: Decide what statements will be executed in the loop. This is
done when the program compares the current value displayed on the
counter with its end value. There are set rules to help you determine if the
statement should be executed or not depending on its value.
• If the step value is negative, the statements should be executed if
the counter reads larger than or equal to the end value of the
counter:
• “counter>=end
• If the step value is non-negative (positive or 0), the statements are
executed if the counter is smaller than or equal to the end value.
• “counter<=end
• Step 2: The Macro executes the statements within the loop for a
specified number of times. This is based on the criteria set up in Step 1.
• Step 3: The first time the statements are executed, the loop counter
value will be established as the initial value.
As you can see, it is the value of the step that is instrumental in the For…
Next loop process.
When you write you code, the starting value must give designated in the loop
counter. For each subsequent interaction, the counter value will be
determined based on the step you’ve assigned it.

54
• Step 4: One the step has been added, the VBA must reevaluate and
determine whether or not the loop must be executed again. This is done
after each iteration.

The For Each…Next Loop


You can use the For Each Next loop to repeat certain statements for every
element contained within a specific array or collection. Since arrays are
actually sets of values that share a relationship between them, and they are
collections of related objects, this type of loop is more practical than the
For…Next loop.
This loop is very effective in manipulating arrays and is one of the most
efficient means of simplifying your work with collections of similar objects.
Its construct is very similar to the For…Next loop with just a few variations.
The For Each…Next loop makes it possible to work with an array or a
collection even when you can’t determine exactly how many elements it
contains. Without that knowledge, it would be impossible to determine how
many iterations are needed in advance.
The basic syntax for the For Each….Next loop:
“For Each element in group
[statements]
[Exit For]
[statements]
Next [element]
You can use this syntax to delete blank rows, to loop through a Range, to
modify open workbooks, to go through a series of worksheets, to loop
through graphs, to change tiles, to loop through Pivot Tables, Shapes, Combo
Boxes, Checkbooks, Option Buttons, and a whole to more.
Let’s examine closely the different elements of this syntax to see how it
works
Element: these are the variables the loop will use within a relevant group. In
order for this type of loop to work, there must be at least one element
contained within the group that is being used.
The For Each…Next loop does have some restrictions that must be
considered when using data types for the element variable. The data types

55
allowed are determined by the unique characteristics of the group.
• If the group is a collection you can only use:
• Variant variables
• Generic object variables
• Specific object variables
• If the group is an array you can only use Variant variables
Group: The group is simply the group of elements that your system will be
looping. Groups can be either object collections or arrays, however, you will
not be able to use any user-defined arrays due to the fact that a Variant
Variable can never contain any user-defined type.
Statements: These are the actual statements that will be executed within the
group. Statements, for the most part, are an option. You can include as many
statements as you need. In fact, it is possible for you to include statements
that make up loops that will be held within a loop.
Exit for Statement: This is the specific form that allows you to exit a block
or a loop. You can use the Exit For statement in cases where there is no need
to go through all the elements in your group.
You can also use it if your For Each..Next loop is contained within another
loop or as a point of transferring a statement to the Next keyword.
Here’s how it works:
Step 1: Enter the For Each Block. Remember for it to work there
must be at least one element in the group.
Step 2: Execute the Statements for the First Element. Once your code
has been entered, the Macro will begin executing the statements for
the first element.
Step 3: Determine if There are any additional elements to be found
with the group. If there are no other elements, the Macro exits but if
there are more elements, the Macro will continue on to Step 4.
Step 4: Execute Statements for the Next Element
Step 5: Repeat Step 3
As you can see, Step 3 is the key to determining whether the loop will
continue or exit. Every time the statements are executed the Macro checks to
see if there are any elements left in the group. If there are any remaining, the

56
loop will continue and if not, this step alone determines when to exit.

Do While and Do Until Loops


While these are two different loops they are actually two versions of the same
construct. The Do…Loop statement. They have the same purpose of
repeating a single statement (or a group of statements) based on the
conditions being met.
• The Do While loop will repeat the statements while a specific
condition is being met
• The Do Until loop will repeat the statements until a specified
condition is being met or until it becomes True.
As you can see, the primary difference is that the do While loop runs when
the condition is True and the Do Until loop runs only while the condition is
false. Let’s examine the basic syntax of the Do..loop.

Do While and Do Until Syntax #1


“Do [{While | Until}] condition]
[statements]
[Exit Do]
[statements]
Loop

Do While and Do Until Syntax #2


“Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
As you can see, you have two options depending on what exactly you want to
do. You will notice that both syntaxes are very similar with the only distinct
difference being the position where the “[{While | Until} condition]” is
placed.

57
In the first syntax, it is part of the opening statement and in the second it is
placed at the very end of the loop. This positioning is very important since it
indicates the exact position where the condition determines if the statements
within the loop are to be executed again or not.
If the fist syntax applies, it is possible that the contents are never executed but
in the second example, the statements will always be executed.
Understanding this difference is crucial as it determines which version of the
loop you will need to apply.
A Look at the Basic Elements that Make Up the Do While and Do Until
Loop
• The Curly Brackets are used to state which loop you are creating. By
choosing the right word within the brackets. Simply delete the word that
represents the type of loop that you don’t want.
• Do While loop = Do [{While} condition]
• Do Until loop = Do [{Until} condition]
• If you are using the second syntax, it is the last statement that applies.
• Do While loop: Loop [{While} condition]
• Do Until loop: Loop [{Until} condition]
• The condition can be structured in two different ways
• A numeric expression that can be evaluated as numbers
• A string expression that evaluates a sequence of characters
• The condition must be able to return one of the Boolean values of
True or False
• The statements you use within the loop have different values
• The Exit Do statement determines when to exit the loop
• You can use it to create an alternative way to exit the loop
• You can use them anywhere within the loop but it is most
commonly used after evaluating a condition
There are three steps that need to happen before a Do while loop can be
exited
1. Test to see if the condition is true

58
2. Execute the statements
3. Loop or Exit
If you are using the second syntax the steps are as follows:
1. Execute the statements
2. Test the condition
3. Loop or exit

While…Wend Loops
There is one more type of loop you need to be familiar with. The While…
Wend loop. Most people understand the meaning of while but the word
“wend” throws some of them off. It is actually a contraction combining the
words While…End.
This type of loop is primarily used for compatibility with other programming
languages. It is usually used to execute specific statements as long as a
certain conduit are True. The loop will automatically be exited if any of the
conditions are not met. It is not a common occurrence when you need to use
the While…Wend loop but we’ll give a brief overview of it so if you come
across it, you’ll at least have an idea of how it is used.
The basic syntax of the While…Wend Loop:
“While condition
[statements]
Wend
At first glance, you may feel that this syntax is almost exactly the same as
those of other loops but there are some slight differences.
Condition: The condition held within a While…Wend loop is a numeric or
string expression used to evaluate whether a result is True or False.
Statements: As long as the conditions remain True, the statements applied in
the loop will be executed repeatedly.
This type of Loop follows several basic steps:
1. Check whether the condition is True
2. Execute all statements
3. Repeat Step 1 or Exit

59
The Exit Statement and Nesting
As is true with most constructs in the Visual Basic, once you have mastered
the basics, you can start creating your own loops, making them more
complex as you go. But as you create your loops, you need to give careful
consideration to how to exit the loop.
The Exit for statement is the tool that allows you to exit the For Each…Next
or the For…Next loop. The Exit Do statement is used to exit a Do While or
Do Until loop.
There are some basic rules you must follow in order to create the right exit
statement for the loops you create.
• A For…Next loop is exited when the current value on the loop counter
is larger than the end value of the counter (if positive) or smaller than the
end value of the counter if the loop is running backward (if negative.
• A For Each…Next loop is exited once the statements are executed for
the last group element.
• A Do While loop is exited when the relevant condition is no longer
met
• A Do Until loop is exited when the applicable condition is met.

Nesting
You may come across this term from time to time. Nesting is a structure that
allows a loop to be placed within another loop. The loop inside the loop is
considered nesting while the external loop is referred to as the “outer loop.”
There are several conditions that will allow you to nest one loop inside the
other.
• For…Next or For Each…Next loops can work within other For…Next
or For Each…Next loops
• For..Next or For Each…Net can work within Do While or Do Until
loops
• Do While or Do Until loops work within other Do While or Do Until
loops
• Do While or Do Until loops work within For..Next or For Each..Next
loops

60
While you can nest loops inside one another, you still need to be careful not
to overlap control structures. Remember, each nested loop must “close &
terminate with its outer nested level.” This means that the nested loop has to
still be able to be compatible with the outer loop for it to work. So, you’ll
have to be very organized and careful so that you can be sure that each loop
is clearly differentiated and works well within the set parameters.

61
Conclusion
Thank for making it through to the end of Excel VBA: A Comprehensive
Beginner’s Guide to Learn and Understand Excel Visual Basic Applications,
let’s hope it was informative and able to provide you with all of the tools you
need to achieve your goals whatever it may be.
There is so much more you can learn when you master Microsoft’s Excel
VBA. Here in the pages of this book, we’ve only scratched the surface but
hopefully, we’ve given you enough information to get started. Most people,
after learning just a little bit about Excel VBA will comment that they had no
idea of the many capabilities of Excel.
The fact is that it is a bit of a mystery to most people. Without knowing the
minute details of its functions you may wonder why you need to learn it at
all. Just to review, let’s go over some of the things we have learned in these
pages.
VBA or Visual Basic Applications is an impressive computer programming
language that makes it possible for you to program specific tasks and
activities in Excel. With VBA you can create customized worksheets that can
be tailor made to meet your needs.
Most people use VBA to automate certain actions, which allow them to avoid
repeating tasks over and over again every time they are needed.
In the work environment, this feature is invaluable and can literally make life
easier for everyone. It literally
• Automates procedures
• Speeds up the work being done
• Customizes Excel
Here, we have learned the basic format for writing VBA code as well as:
• How to use Data Types, Constants, and Variables
• What are Arrays and How to write them
• The different operators and their purpose
• How to write subroutines and functions
• How mathematical functions are used

62
• How to format functions
• String manipulation
• How to write decision making codes
Now, you’re probably already thinking of even more information that you
can write code for. It is much easier than you might have thought. Chances
are though, you will have to cover this material several times before it sticks
and becomes second nature to you but don’t stop here. There is so much more
that can be done with visual Basic that the pages of one book could not
contain it all. At the very least, we hope we’ve peaked your interest so that
you know that anyone with a mind to do it could master writing code in Excel
VBA.
It is the one program that doesn’t require specialized knowledge or skills.
You’ve probably got everything you need already at your fingertips. So, now
it’s up to you to take it to the next level.
Finally, if you found this book useful in anyway, a review on Amazon is
always appreciated!

63
Excel VBA

Tips and Tricks to Learn and Understand


Excel VBA for Business Analysis

64
Introduction
Congratulations on purchasing Excel VBA: Tips and Tricks to Learn and
Understand Excel VBA for Business Analysis and thank you for doing so.
It seems that we often take for granted those things that are readily available
to us. The things we really don’t give that much attention, assuming that they
will always be at our disposal. I suppose that is what has happened with
Microsoft’s Excel VBA. People seem to know that the features they use only
scratch the surface of this software’s incredible capabilities but few realize
just how much they are missing out on.
As business owners, we are usually running at top speed, the concept of
taking the time to learn something new, especially when we have found a
way to manage all of our tasks, can feel like an exercise in futility. However,
many might be surprised to learn that the heavy workload can easily be
lessened just by learning some of even the most basic elements of the Excel
program.
Using Excel VBA in your business could turn out to be the very thing that
helps you boost your productivity and efficiency levels. It can save you
hundreds, if not thousands of hours in manpower, something that can free up
your time and resources so you can focus on the reason you went into
business in the first place.
Whether you feel your time would be better spent doing the same thing
you’ve always done or you’re looking for new ways to make your business
run smoother, learning about Excel’s VBA program may very well be the
answer to your prayers.
Here, in this book, we plan to discuss all you need to know to take advantage
of this amazing tool. You will learn how to automate the very steps you have
already been doing so that your business will be able to run at top speeds.
You will learn to write your own code so that your Excel programs can be
tailor made to match your unique business needs, and you will be able to take
advantage of the many different ways you can utilize features like string
manipulation and looping.
Finally, you will learn how to troubleshoot problems we all have when
navigating the challenges of Excel VBA and give you a few tricks on exactly
how to avoid them when creating your own lines of code.

65
No doubt, there is a reason why you downloaded this book. Maybe you’re
trying to find a way to enhance your business practices or you’re looking for
a better way to get your tasks done. You may simply be curious about all the
talk about Excel VBA and came here for a closer look. Whatever your case,
just know that you’re in for an exciting adventure into the wonderful world of
Visual Basic Applications. At the very least, you will finish this journey with
a whole new perspective on the power you can give your business with this
amazing tool.
There are plenty of books on this subject on the market, thanks again for
choosing this one! Every effort was made to ensure it is full of as much
useful information as possible, please enjoy!

66
Chapter 1

67
Visual Basic Applications - The Basics

It is quite clear that there are a lot of things you can do with Excel. Ever since
its first introduction in 1985, we’ve heard people praise its impressive
capabilities. With just a basic knowledge of formulas, there are countless
different tasks that can make sorting, moving data, and analyzing it about as
easy as brushing your teeth.
At first glance, a look at an Excel spreadsheet can seem quite daunting but
once you have mastered the basics there is a whole new level of skills that
can be accessed to take your business even further. Once you learn how to
use VBA, an extension of the already formidable program, you’ll wonder
why you ever hesitated to use it before.
If you are using Microsoft’s Excel VBA 2010 or later, the programming
language used is Visual Basic 6. Once you get the basics down, you will be
able to program your computer to perform a wide variety of functions that
can expand your business capabilities.

Let’s Get Started


Later in this book, we will go into more complex Visual Basic code but
before we can do that, it is important that we at least review the basics of
VBA programming. In this chapter, we will review a few of the more
fundamental programming techniques so you are ready to move on to the
more advanced skills.

A Word About Macros


Since writing Macros is at the very core of using Excel VBA, you must
remember that there is a certain level of risk you accept when you record
your own Macros. Because there is the probability that if used incorrectly, to
accidentally lose files or alter them in such a way that they can be rendered
unusable Microsoft has a built in precaution in place. For this reason, they are
not included as a default mechanism in your Excel VBA file. So, before you
can even begin to write Macros, you will need to first enable them in your
system.
To do this, you will need to first open your Excel program and go to the File
tab in the upper left part of your screen. Under File, select OPTIONS, and
then choose CUSTOMIZE RIBBON. Look for a small box labeled Developer

68
and click on it. This will place the developer option on the main page. As a
review, follow these steps:
• Go to the FILE tab on your main screen
• Select OPTIONS
• Choose CUSTOMIZE RIBBON
• Check the box labeled Developer
• Click OK at the bottom of the screen
• Return to the main screen
You should now be able to see the Developer tab on the main screen next to
the VIEW tab on the far right.
Once your Developer tab is set up, make sure that your version of Excel has
the ability to run the Macros you will be creating. To do this, you must go
back to the FILE tab, select options, and then choose the TRUST CENTER
followed by TRUST CENTER SETTINGS. In the settings window, click on
Macros and then enable. When you return to the main screen, you should see
both the ribbon and the run program options that will allow you to run any
Macros you plan to write. There are a lot of steps involved in this set up so
let’s go over them again to make sure you have the order exactly right.
• Go to the FILE tab on your main screen
• Select OPTIONS
• Choose TRUST Center
• Select TRUST CENTER SETTINGS
• Click on Macros
• Click on enable
The resultant screen should appear like the image below

Now, you are ready to begin writing your own code. When writing your first
program, it is best to write one that is simple but with enough complexity that
you will be able to learn the tricks of the trade at the same time. As a

69
beginner, it might be best when writing your VBA program, to do your work
in a module rather than in a standard worksheet. This is because modules
allow you to monitor your work as it unfolds so you can catch errors before
they become real problems.
To begin to write your program, you will need to go back to the VBA Editor
screen. This time, you want to click on INSERT, then choose MACRO
MODULE. As soon as you do that, a totally blank page of a new module will
appear along with a new set of options. Do that now and look for the options
to appear right next to the UNDO and REDO buttons. You’ll see several
options including stop and pause, which we will discuss in a little more detail
soon.
Modules have their own names but will probably be initially seen numbered
as in Module1, Module2, Module3, etc. If you’d prefer another name you can
change it by going to the box labeled PROPERTIES in the bottom left of the
screen, and simply replacing it with a name you’ve chosen.
If you choose to work with Modules rather than spreadsheets, you need to
understand the differences between them. It is important to understand that
modules do not contain cells like you would see in a normal spreadsheet.
They are also not programed to calculate the many formulas Excel is known
for. Actually, modules work more like a traditional word processor. At first
glance, that may not mean much but as soon as you begin typing your code,
you’ll notice the difference. You will be able to type in full lines of text and
make any edits you want using the standard options of CUT, COPY, PASTE,
and DELETE. When you are ready to save your work, you will find that the
module will be automatically saved along with any other documents or pages
that may be needed to run the program.
When you begin writing a program, you’ll find that the module will
automatically begin to compare what you are typing with other VBA
commands and it will alert you if make a mistake with the code you write. If
you’re an expert programmer, this won’t mean much to you, but this type of
alert can prove to be invaluable for the beginner, who is much more likely to
make mistakes. This way, you can correct the problem when it happens rather
than getting to the end of your code and having to backtrack to find the error.
For that reason, the first line of every program you create in a module needs
to begin in exactly the same way.
Sub name ()

70
Keep in mind that this is a standard format and you will substitute the actual
name of your module with the word name. So, if your first module is named
“test” then you would start your program with:
Sub test ()
Most people prefer to start their first module with “hello.” So, the first line of
their code would read:
Sub hello ()
You also have to be consistent in writing your code in the same way. The
same is true for when you are ready to end your program so the final line of
your code should read:
End Sub
It is not possible to change this line as this is what alerts the program that its
work is finished. If you fail to include this phrase Excel will continue running
expecting more work to be done. You will know that your entries are correct
when they turn blue.
These two entries are fixed commands that have been pre-programmed into
VBA. Study these lines and memorize them. If you forget to include the
parenthesis at the end of your first line, the program will automatically add
them for you. You won’t be able to proceed without them. The same will be
true for the End Sub line. The program will look for it and if it is not present,
then it will try to decide if it needs to add this information to complete your
code. As you become more familiar with what is correct language, you’ll find
you’ll be able to write code incredibly fast.
At this point, you have the beginning and the end of your first written code
for your new program. You can now turn your focus on the meat of your
code, the part that fits in the middle. This is the part of the program that tells
the system exactly what to do. As you learn how to write this section, keep in
mind that you will not be writing to another human but to a program that
needs to see it as a list of instructions. Since computers cannot reason in the
same way as the human brain does, it must be able to understand the
commands you give it.
While you can program the code to do whatever you like, you must code it in
a language that is different from the way we normally think. The best way to
do this is through the MsgBox command function. When the system reads
MsgBox, the module knows that it must create a specific message, which will

71
include the text you want to program to display.
Once you understand this, writing code suddenly becomes easy. All you need
to do is key in MsgBox followed by whatever you want to be displayed on
the screen. Your code could look something like this:
Sub test ()
MsgBox “Welcome”
End Sub
A simple enough program to start with but with enough detail to test it out to
make sure everything is done right. To test it, you’ll need to go up to the
toolbar and click on play. On some older versions of VBA, this option may
not be visible. If that’s the case, click on the VIEW tab, then TOOLBARS,
and then look for the VBA option. Another way to test your program is by
pressing the F5 key or selecting RUN, then start.
Once you’ve started the test, you will see a dialog box that will give you a list
of modules. Select your module and then click on RUN. You should see the
message box appear at the top of the window displaying the message you
wrote in your code. “Welcome.” It should have a title bar and an OK button.
Click on OK to end the program.
If you wrote more than one message, then once you click OK, the next
message will automatically appear. If this does not happen, then you will
have to go back to your code to see if you entered your message correctly.
Now that you understand the basics of writing code, it’s time to kick it up a
notch. It’s time to create a situation where a user can interact with the
program. To do this, you need to use another type of input value that is
similar to the MsgBox, called the InputBox.
For this, you need a special command:
A = InputBox
This type of message will allow you to input a question into a box so that
whoever uses the program later can write a response. It is important to think
about the question you ask. For starters, we will use questions that will only
yield a numerical response. For example, “how many classes do you have.”
This way, when the user enters a response and hits enter, the program will
automatically save the answer and label it as variable A.
Variables are a key component when creating your own macros. You could

72
think of them as working similar to a cell in your workbook but with one
major difference. Variables in VBA are not connected to any particular
worksheet but can be utilized anywhere within the entire workbook.
Care must be taken when creating a variable. When you are working on a
module, it will store and track all of the data and without accessing a regular
spreadsheet. To create one, all you have to do is name it and then use it.
There are a few basic rules you must follow when naming a variable:
• The first character must always be a letter
• After the first letter, the rest of the name could be comprised of letters
and numbers
• The name could be as long as you want it
• No spaces are allowed
• Uppercase and lowercase letters are used
• Constant variables are usually named with all uppercase letters
• You can’t use a java keyword
• Underscores can be used but no other symbols
Once a value has been entered and stored, you will be able to access it from
any macro used within the same module. Your program could look
something like this:
Sub hello ()
Children = InputBox(“How many children do you have”)
MsgBox Children
End Sub
You can see that we changed the original message with a question, asking the
user to key in the number of children they have. Once they press enter, that
variable is now saved under the label “children. “This process is relatively
easy to do but when you examine it more closely, you’ll realize that several
things must happen at exactly the same time for the program to work.
• The MsgBox does no longer display its name but the number answer
instead.
• This could be compared to a user manually inputting the number
directly into the A1 cell on the worksheet.

73
Let’s try to make our code just a little bit more complex. As you can see, the
ability to add input and output makes it possible for you to create a myriad of
different macros. But it can get much more exciting when you see how you
can get your code to interact directly with Excel. When you use Excel VBA,
you will have the ability to make sure that everyone who uses your program
has their input data placed exactly where it needs to be. Here is an example of
what this type of code would look like.
Sub hello()
MsgBox “Real Estate sales this year”
Sales = InputBox(“How many sales did you have this year”)
Amount = InputBox(“What is the purchase price for each
home”
Commission = (“InputBox(How much commission did you
earn.)
Interest = (“How much interest will the bank charge”)
MsgBox “Total number of Real Estate sales this year”
End Sub
In this example, the lines were written out to make it easier to read, however,
when you are creating a macro in a module, it is easy to finish a line without
clearly writing the command. This is okay but if you reach the end of a line
and your command is not completed, you must continue the command on the
following line before you input anything else, otherwise, the module will not
be able to read it correctly, which could end up causing a bug in your
programming.
If you follow these basic guidelines, when you run the program, the first
thing you will see is a message box detailing the reason for the program. This
will be followed by a series of input boxes giving a blow-by-blow
requirement to the user. When the user has answered all the questions
required of them you should automatically receive the results.
Of course, this is a very simple example but a good one to get started with.
Practice these instructions until you feel comfortable with them. As you write
new code and run them, you will begin to see exactly how the computer
responds to your requests and what needs to be changed. In time, you will be
able to predict exactly what the program will do and when. If it doesn’t work,
you’ll know exactly where to look to find the problem.

74
Understanding Variables
When it comes to variables there are two terms that you will have to be
familiar with:
• Declaring: the process of informing the system that it needs to pay
extra attention to a particular component of the coding.
• Initializing: the process of giving an initial value to a variable.
Variables are a big part of writing code in VBA so you’ll have to learn how
to use them well. There is a definite process involved in writing variables and
we’ll try to go through the basics one by one. First, let’s get you familiar with
some features of the program you will be using.
1. The Command Button: You will need to place a command button on
your worksheet. To do this, you will start with the following steps:
• Click on the Developer tab
• Select the Insert button
• Find the ActiveX controls
• Select the Command Button option
• Drag the command button and place it where you want it on your
worksheet
You now have the command button where you can work with it. At this
point, realize that it is not yet linked to any macro, you will need to link it
manually before you can continue on. To do this follow these steps:
• Make sure you are working in Design Mode
• Right click on the command button
• Select View Code
• This action will open up the Visual Basic Editor
• Two phrases will appear that look like this…
Private Sub CommandButton1-Click()
End Sub
• Place your cursor on the line in between these two phrases
• Enter this code:
Range(“A1”).Value=“Hello:

75
Another window will open giving you a list of any sheet names that are
currently active. This list is referred to as the Project Explorer and its purpose
is to give you a means of determining which of these sheets you are currently
writing code on. Since the Project Explorer does not always appear
automatically, you may have to open it yourself.
• Select the View tab
• Choose Project Explorer from the list
Once you’re sure you’re writing code in the correct sheet, enter your code.
Deselect Design Mode and click on the command button. Now, look in cell
A1 and you should see the word “hello” appear. Congratulations, you have
just entered your first variable!
Now, that you understand how to enter them, it is important for you to know
the different types of variables and how they are used when writing code.
Integer Variables: An integer is simply a whole number so an integer
variable is used when you are dealing with whole numbers and not fractions.
Your code should look similar to this:
Dim x As Integer
Z=5
Range(“B2”).Value = Z
With this code, the integer 5 is placed in the cell B2. Let’s take a closer look
at this code and how it is put together. First, notice that the initial line of code
declares the variable labeled “Z” and the next line identifies the integer. It
then initializes the value 5 for Z and then determines the location where the
result will be entered.
As you write your own code, you can change the range (the location where
you want the result), the value, or the integer. With this as a basis, you can
now extend your writing to automatically input any type of variable you need
as long as you’re using whole numbers or integers.
String Variables: When you want to store text rather than numbers, you
would use a string variable. Codes could look something like this:
Dim book As String
Dog = “Labrador”
Range(“A1”).Value = dog

76
The system would then place the word dog in the A1 cell. If you had
previously written any other word in that cell, it would automatically change
it to the variable you provide in your new code. As you study this code, you
will notice the first line declares the variable, the second initializes the
variable with text, and the final line gives the location for the result.
Double Variables: These are practical when you need a very precise variable,
something more than an integer. With this type of variable, you will get a
dialogue box that indicates your chosen value that will alert you that your
chosen integer is not sufficient for the value you’ve chosen, allowing you to
adjust it to compensate. This might be better understood by an example:
Dim X As Integer
x=6=2
MsgBox “value is” & Z
In this example, the program will automatically give you a dialogue box
showing that your chosen value of 6 is not correct. You will need to key in an
addition to the integer to make sure that the system will give you the right
answer. Your adjusted code would look something like this:
Dim X As Double
X = 6.2
MsgBox “value is” & Z
This new adjustment tells the program to look for a decimal and give you the
correct answer of 6.2. Obviously, this type of variable is used when you are
dealing with more than whole numbers. It’s important to understand that the
double variable works when you’re only dealing with a single decimal point.
If you need a result that will give you more than that, you will need to use a
long variable instead.
Boolean variables: Whenever you want your variable to yield a true or false
answer, you need a Boolean variable. The format of the code looks like this:
Dim continue As Boolean
Continue = True
If continue = True the MsgBox “Boolean variables are cool”
This type of code will give you a dialog box containing the sentence
“Boolean variables are cool.” Here, the first line declares the Boolean

77
variable. The second line initializes it as true, and the third line ensures that if
the result is true, the specified message will be displayed.
As you can see, there are many different types of variables you can use. Since
computers cannot tell the difference between numbers like (1, 2, 3, 4…) and
strings (a, b, c, d…) the program distinguishes them as Data Types. However,
they can all be categorized into two different categories: Numeric and non-
numeric Data Types. You need to not only know the different data types but
also the amount of storage they use and their range of values.

Numeric Data Types


Data Number Range of Values
Types of Bytes
Used
Byte 1 byte 0 - 255
Integer 2 bytes -32.768 - 32,767
Long 4 bytes -2,147,483,648 - 2,147,483,648

Single 4 bytes -3.402823E+38 - -1.401298E For


negative
values
Single 4 bytes 1.401298E-45 to 3.402823E + 38 For
positive
values
Double 8 bytes -2.7976313486232e + 308 - For
-4.94065645841247E - 324 negative
values
Double 8 bytes 4.9406564584124E - 324 - For
1.79769313486232e + 308 positive
values
Currency 8 bytes -922,337,203,6685,477.5808 -
922,337,203,685,477.5807

Decimal 12 bytes +/- If no


79,228,162,514,264,337,593,543,950,335 decimal
is used
Decimal 12 bytes +- 7.9228162514264337593543950335 28
decimal
places

When using VBA, if you do not specify the data type, the program will
automatically make the decision to declare the variable as a Variant.

78
In business, this can be a very instrumental tool in many ways. For each
process or service that you offer your clientele, you can use these different
variables to capture any data related to your business and store it in a way
that gives you easy access.

Understanding Statements
Another major part of coding is creating statements. Statements simply give
the computer instructions on what to do. Each statement will contain either a
constant, expression, keyword, operator or the variables that will make it
clear what the program needs to do. Statements can be divided up into two
categories:
• Declaration Statements: name variables, constants, or procedures.
They can also be used to specify data types.
• Executable Statements: initiate actions. They can call up a certain
method or function, loop, or branch through blocks of code. Some
executable statements can assign value or expressions to either
variables or constants.
Let’s take a look at some Declaration Statements. These can be used to name
and define certain procedures, variables, properties, arrays or constants.
Declared Statements have very specific characteristics that can affect the
code and determine how it interacts with it. Every declared statement must
have at least one of the following:
Data type: the unique values held in the element and a means of storing those
values
Lifetime: a set period of execution time when the element is available to be
used
Scope: a set of code that refers to the element without the need to qualify the
name
Access Level: Permission for the code to use the element
Below is an example of how declaration statements can be made. This code
has three different declarations inside of it.
Public Sub applyFormat(1)
Const limit As Integer = 33
Dim thisWidget As New widget

79
‘ Insert code to implement the procedure.
End Sub
Can you identify the three declaration statements? The first is the Sub
statement with two parts, which instructs the program to begin. The End Sub
is the part that tells the applyFormat procedure to stop. The code also makes
it clear that the applyFormat is Public, which makes it possible for any other
code that can reference to also be able to access it.
The second declaration is seen as the Const statement. It declares the constant
limit and assigns a value of 33 to the Integer data type.
The third declaration can be seen as the Dim statement. It declares and labels
the variable as thisWidget specifying an object that was created from the
widget class.
When writing code, you are free to declare a variable to be any sort of data or
object type found in the application you are using.
Now, let’s take a closer look at some of the most common statements you
will come across when writing code.
If…then statements: You can use these when you want to write a code that
will activate a program only under specific conditions. To do this, you need
to first create a button in your worksheet and then add the following code
format:
Dim score as Integer, result As String
Grade = Range(“B3”).Value
If Grade >=70 Then result = “pass”
Range(“B3”).Value = result
In this example, if the grade is 70 or above the student is given a pass. So, if
the integer found in cell A1 is 80, then pressing the enter button will result in
the word “pass” being automatically added to cell B1. If the score falls below
70 you can add another result that will look something like this:
If Grade<70 Then result = “fail”
In this case, the word “fail” will be entered into cell B1. This part, however,
is optional. If there is no directive given beyond pass, the cell B1 will simply
remain blank.
There are many applications for if…then statements in your business. The

80
example above applies to schools and classes, but the same application can
also be used in medical offices, retail establishments, financial institutions
and many more. Since you are writing your own code, you will simply adapt
the statements to your business needs.
Else statements: There is an even easier way when you know you will have
more than one result in your program. Else statements are more commonly
used when you are expecting multiple outcomes in a program. Let’s examine
the following example.
Dim score As Integer, result As String
Score = Range(“A1”).Value
If score>=70 Then
Result = “pass”
Else
Result = “fail”
End If
Range(“B1”).Value = result
As you can see, you have now assigned a value of pass to all cells that fall
within a set range showing anything above 70. The additional Else statement
lets the program know that anything that falls below that range should
automatically receive a fail. To add an Else statement, place it immediately
after the Then statement and delete the End If. You will have to create a
completely new line after the Else statement to make sure your End is placed
exactly where it belongs.

Looping
Another extremely useful tool when writing code is looping. This technique
allows you to create a program that will “loop” through several different
ranges repeatedly without having to add an extensive amount of code. So, if
you have an action that needs to repeat, rather than having to input code for
each cycle you want to be repeated, you can write a loop code that will
automatically tell the program exactly how many times to loop or to continue
the process until it reaches a certain conclusion. Just like with variables, there
are several different types of loops you can write.
Single Loop: When your loop needs to move through a one-dimensional

81
range of cells, you can create a single loop. Here is an example:
im i As Integer
For j = 2 To 7
Cells(j, 1).Value = 75
Next i
This code will generate an integer (75) and place it in the J2 - J7 range of
blocks. This starts an execution of the codes written in between the For and
Next, which will be repeated for a total of 6 times.
The first time j = 1 tells the program to place the integer 75 in a cell where
the related column and row actually meet. This is the first execution. The
second execution will happen automatically when the program accesses the
second 2. It will then increase the amount by 1 and go back to the For
statement. When the result is j = 2, the program will enter the integer 75 into
the next cell where the row and column intersect again. This process will
repeat (or loop) again until all the cells from 2 - 7 are filled.
Double Loop: The double loop is one that has to work through a two or
multi-dimensional range. Here is an example of one:
Dim j As Integer, k As Integer
For j = 2 To 7
For k = 1 To 2
Cells(j,k).Value = 75
Next k
Next j
This code will fill the rows 2 to 7 in columns j and k with the integer. The
code tells the program that when j is equal to 2 and k is equal to 1, it needs to
add the number 75 at the point where the row and column meet for the first
time. When the program gets to the second k, the value increases by 1 and
returns to the For section of the k statement. This time, when j = 2 and k = 2,
the program will place the 75 at the point where the next row and column
intersect. From this point on, the program will run between 1 and 2 and
repeat until it runs out of j columns that have been a part of the set conditions.
Triple Loop: This loop works in exactly the same way as the double loop but
across several different worksheets. To create one, use the following code as

82
an example:
Dim d As Integer, J As Integer, k As Integer
For d = 2 To 4
For j = 2 To 7
For k = 2 To 3
Worksheets(d).Cells(j,k).Value = 75
Next k
Next j
Next d
As you compare this with the double loop, the only difference that stands out
is the addition of several different worksheets. This statement must come
before Cells so that the first sheet will have a two-dimensional range when it
comes to c = 1, c = 2 on the second sheet and c = 4 for the third one.
Do While Loop: All of the previous loops have been a different version of
the For…Next loop but there are several other loops you also need to be
familiar with. The Do…While loop instructs the program to continue to
repeat the action for as long as a set factor remains true. All that is needed to
create a Do…While loop is to place the code inside of the already existing
code at the proper place. Let’s try this with a code we’ve already previously
used.
Dim i Integer
J=2
Do While j < 7
Cells(j,2).Value = 25
j=j+1
Loop
This code will cause the program to place the number 25 in the relevant cells
in a predetermined set of rows. The condition set states that as long as the
value of j remains less than 7, the program will place the integer 25 into the
cell at the point where the row and column meet for the first time. It will do
this again on each additional row as long as the value of j continues to be less
than 7.

83
This is a good time to explain that the symbol = does not necessarily mean
equal as in exactly the same but it actually means that the value “becomes”
whatever follows. This can help to clarify the use of the code more clearly.
The value of J may change throughout the program but at the point when it
becomes j + 1 is where the action will take place. So, if j = 1 at the start of the
program, then j becomes 1 + 1 = 2 during the next loop. This program will
continue until it reaches the point where j = 7 before the loop will actually
end.

84
Chapter 2

85
String Manipulation

Before you can manipulate strings you need to understand exactly what they
are. They have a very specific purpose that is very necessary when it comes
to writing code. It helps to compare them to the way we normally
communicate with each other. While we use words in conversation, we are
more likely forming them not individually but through a complex sentence
structure.
With that in mind, when you need to communicate via a computer code you
want to think not just about the words you use but about the way the
sentences are structured so that they deliver a complete thought.
Strings are an important part of VBA code. They make it possible to create
more advanced operations like parsing to an array, removing blanks,
formatting dates, finding characters within a string, making comparisons, and
extracting parts. There are several different functions connected to string
manipulation that will make all of these actions much easier to do.
Keep in mind, when manipulating strings, the program functions you will use
cannot alter the primary string in any way. Rather than tamper with the
primary string, you will create an entirely new string that contains the same
elements you needed when you performed your initial search. You will need
to reassign the location of the new string so that the results are saved to the
same location as the original string.
Basically, a string is a sequence or combination of characters. When you
declare a variable, you must use either a String or a Variant data type. String
Manipulation is a group of problems where the user must process a specific
string and alter its data in some way. Here, we are going to discuss several
different ways to perform a string manipulation.
Joining Strings: In this function, you will be combining two different strings
into one. This is a process referred to as concatenation.
Dim strFirstName As String = “Smith”
Dim strLastName As String = “Smith”
Dim strTitle As String = ‘Mr.”
Dim strSalutation As String
strSalutation = strTitle & “” & strFirstName & “” & strLastName

86
In this example, we see that the strings are comprised of variables but it does
not need to be limited to this type of function. A string can also perform
certain actionable functions. Any string that does this is called a string literal,
which consists of any text string that can be directly added to a pair of quotes
as in the following:
Dim strFirstName As String = “Fred”
Dim strLastName As String = “Smith”
Dim strTitle As String = “Mr.”
Dim strSalutation As String
strSalutation = “Hello” & strTitle & “ “ & strFirstName & “ “ &
strLastName
As you can see from the above example, the string manipulation has allowed
all of the above listed strings to be merged into a single string.
When you write code, data inputted by the user could end up in several
different places across a wide variety of worksheets. By using this type of
string manipulation you are now able to compile specific data you need into
one location where you can have easy access to it, saving you loads of time
and money in the process.
Finding the length of a string: When working with extremely long strings,
you may need to find a particular character or a few specific characters within
it. This could be a time consuming and cumbersome task, to say the least.
However, with Excel VBA, you have several options that will allow you to
find those characters without the need to have to read the entire string. You
can also determine exactly how long a particular string is with the use of
these functions.
The function Len() looks at the string as if it were an argument between two
people.
Dim decLength As Decimal
decLength = Len(“This is a string literal”)
The technique works the same when you’re working with string variables:
Dim decLength As Decimal
Dim strMyString As String = “This is a String Variable Value”
decLength - Len (strMyString)

87
Comparing strings: When you need to compare two or more strings you
must use the optional compare parameter. It is of the utmost importance that
these parameters are set up correctly. In cases where you use the
vbTextCompare device, it doesn’t matter if you are using upper or lower case
letters as the system will read everything in the same way. However, if you
opt to use the vbBinaryCompare you will have to take extra care with the
values you input as in this case, the system reads it all differently.
Let’s put these two options together so you can understand what I mean here.
Sub Comp1()
‘Prints o : Strings match
Debug.Print StrComp(“ABC”, “abc”, vbBinaryCompare)
‘Prints -1: Strings do not match
Debug.Print StrComp(“ABC”, “abc”, vbBinaryCompare)
End Sub
As you can see from the above examples, you can avoid having to adjust the
parameter for every instance by simply using the setting for Option Compare.
Once this code is structured, correctly, each function that utilizes the compare
parameters you set will then automatically adjust their new settings by
default.
You can use this Option Compare commands in two different ways: with the
Option Compare Text command, which actually changes the system’s default
compare settings to vbTextCompare as you can see in the following example:
Option Compare Text
Sub Comp2()
‘Strings match - uses vbCompareText as Compare argument
Debug.Print StrComp(“ABC”, “abc”)
Debug.Print StrComp(“DEF”, “def”)
End Sub
The other way is to switch the default compare settings to vbBinaryCompare,
which allows you to program the system to compare the binary elements of
the string.
Option Compare Binary

88
Sub Comp2()
‘Strings do not match - uses vbCompareBinary as Compare
argument
Debug.Print StrComp(“ABC”, “abc”)
Debug.Print StrComp(“DEF”, “def”)
End Sub
Once you grasp the idea behind each of these options, you will be able to see
more clearly how each string function can be distinguished from others by
the way it works.
Appending String: When you need to add data to an already existing string,
you are appending the string. This can be done by simply applying the
ampersand symbol (&) and using it as the operator. See how this is done in
the following example:
Sub Append()
Debug.Print “ABC” & “DEF”
Debug.Pring “Jane” & “”& “Smith”
Debug.Print “Long” & 22
Debug.Print “Double” & 14.99
Debug.Pring “Date” & #12/12/2018#
End Sub
From this example, notice how the different categories of data are stored. If
you look at the numbers and dates, you’ll see that they are turned into strings
immediately. This makes it possible for the program to ready them more
easily. You might at times see this type of code with a (+) sign as the
operator. This format is useful when trying to append strings. The only major
difference between using the “+” sign is that it only works with string types
otherwise it will produce an error message that looks something like this:
“Type Mismatch”
Debug.Print “Long” + 22
When You Need to Extract Parts From a String: There may come a time
when you may need only a specific part of a string. Remember, strings are a
compilation of a lot of different data into one single code. So, for example,

89
the string may include data about a particular product, price, and vendor all in
one string but you only need the data related to the vendor to complete a
specific task. Being able to extract only that part of the string could save you
a lot of time and prevent you from having to literally reinvent the wheel. The
following functions listed in this section are very practical when you want to
extract parts of a string. For the more difficult types of extractions, it is best
to avoid using VBA InStr and follow a specified set of parameters.
• If you plan to extract the left part of a string then the parameters should
look like this:
Function: left
Parameters: string, length
Description: Return characters from the left side
Sample code: Left(“sample text”,5)
• If you plan to extract the right part of a string then use the guidelines
below:
Function: right
Parameters: string, length
Description: Return characters from the right side
Sample code: Right(“sample text”,4)
• If you need to pull out a middle section:
Function: middle
Parameters: string, start, length
Description: Return characters from the middle
Sample code: Mid(“sample text”),5,4)
Whether you are extracting from the middle, the left or the right, the
functions you perform will extract whatever section of the string you
disunite. If you examine the parameters above, you will see that the code you
input will start searching for the section at the exact point you designate and
the left and right functions will start from the side you assign for the program
to search. Look at the example code below to see how this works.
Sub UseLeftRightMid()

90
Dim sCustomer As String
sCustomer = “John Thomas Smith”
Debug.Print Left(sCustomer, 4) ‘ Prints: John
Debug.Print Right(sCustomer, 5) ‘Prints: Smith
Debug.Print Left(sCustomer, 11) ‘ Prints: John Thomas
Debug.Print Right(sCustomer, 12) ‘Prints: Thomas Smith
Debug.Print Mid(sCustomer, 1, 4) ‘Prints: John
Debug.Print Mid(sCustomer, 6, 6) ‘Prints: Thomas
Debug.Print Mid(sCustomer, 13, 5) ‘Prints: Smith
End Sub
Keep in mind that these functions do not have the capability of altering the
initial or primary string unless you program them to do so. As you can see
from the code, the program is given the exact parameters of information you
want to extract. It knows exactly how many spaces to count from any starting
point on the string and how many characters to extract and it knows exactly
where to place the extracted data. You will be able to see this in the following
examples:
Sub UsingLeftExample()
Dim Fullname As String
Fullname = “John Smith”
Debug.Print “Firstname is: “; Left(Fullname,4)
‘ Original string has not changed
Debug.Print “Fullname is: “; Fullname
End Sub
In this case, if it is necessary to change the primary string then the return
value must be assigned to the function as in the example below:
Sub ChangingString()
Dim name As String
name = “John Smith”

91
‘ Assign return string to the name variable
name - Left(name, 4)
Debug.Print “Name is: “; name
End Sub
Searching for data held within a string: Two VBA functions, the InStrRev
and the InStr, are commonly used when you need to search a string to find a
particular sub-string. Once the specific string is found, its details will be
displayed showing its precise location in the string. If for some reason, the
substring cannot be found then the program will display a 0 or if the string is
null then it will display the word null instead.
Here are the parameters if you choose to use InStr:
• The starting position for the search will begin at the number 1 position if
there is no parameter set
• String1 As String indicates which string the program will search
• String 2 As String indicates what the program should search for
• Compare As vbCompareMethod
The purpose of the InStr is to return the first position it finds of a specific
string as in the case below:
Sub FindSubString()
Dim name As String
name = “John Smith”
‘ Returns 3 - position of first h
Debug.Print InStr(name, “h”)
‘ Returns 10 - position of first h starting from position 4
Debug.Print InStr(4, name, “h”)
‘ Returns 8
Debug.Print InStr(name, “it”)
‘ Returns 6
Debug.Print InStr(name, “Smith”)

92
‘ Returns 0 - string “SSS” not found
Debug.Print InStr(name, “SSS”)
End Sub
The parameters for the InStrRev are as follows:
• StringCheck As String identifies the string that is to be searched
• StringMatch indicates what the program will search for
• Start As Long[Optional - Default is -1] indicates the point where the search
will begin
• Compare As vbCompareMethod
This function is pretty much the same as the InStr function with the only
difference being that the InStrRev starts its search from the end of the string
rather than from the beginning. So, if there is only one occurrence of the
substring in the primary string both functions will yield the same results.
In both cases, learning to use these function can simplify your work
considerably as long as you are doing only basic searches. However, if you’re
planning on conducting more detailed searches they can quickly complicate
matters. In such cases,
Split functions: The split function is used when you need to divide the strings
into an array so you can access specific terms more easily. What actually
happens is the string is divided at a certain point so that each item can be
moved to a new array. Depending on the location, you will have the ability to
access the array and find the part of the string you were looking for. Here is
an example of a split function code:
Dim s As String: s = “John Henry Smith”
Debug.Print Split(s, “ “)(0) ‘ John
Debug.Print Split(s, “ “)(1) ‘ Henry
Debug.Print Split(s, “ “)(2) ‘ Smith
You will notice that the first position, the array, is set to be zero, which is one
of the most common forms of programming a split function.
You should also take note of the fact that the code will split each time it is
used but this is optional. You also have the choice to split the string only
once and then store it as an array variable afterwards. By doing this it allows

93
you to have access to it at a later date when it could prove to be more useful
to you. Below is an example of how to write this type of code:
Sub SplitName()
Dim s As String: s = “John Henry Smith”
Dim arr() As String
arr = Split(s, “ “)
Debug.Print arr(0) ‘ John
Debug.Print arr(1) ‘ Henry
Debug.Print arr(2) ‘ Smith
End Sub
As you can see, by adding just a few extra lines of code you can change the
split function and store it as an array so you have easy access to your data
whenever you need it. Conversely, you can also do this in reverse by building
a string from an existing array with the Join function. It is really just the
process of reversing the Split function and the coding is very basic:
Sub ArrToStr()
Dim Arr(0 To 2) As String
Arr(0) = “John”
Arr(1) = “Henry”
Arr(2) = “Smith”
‘ Build string from array
Dim sNames As String
sNames = Join(Arr, “,”_
Debug.Print sNames
End Sub
Now that you understand the basics, let’s take a closer look at some real life
examples of how you can use this skill in your business.
Accessing pieces of file names: In some businesses, there may be a need to
extract certain number data from a group of files. You may not need all of the
file information but only one part of a few files. String manipulation is a great

94
way to accomplish this. For example:
“VB_23456_Val.xls”
“VV_890_Val.txt”
“VZZA_112233_Val.doc”
Let’s assume that these figures represent the data you want to extract from
the files. To access these values, you use the underscore(_) symbol to split
the string like this:
Sub GetNumber()
‘ Prints 23456
Debug.Print Split(“VB_23456_Val.xls”, “_”)(1)
‘ Prints 890
Debug.Print Split(VV_890_Val.txt”, “_”)(1)
‘ Prints 112233
Debug.Print Split(“ABBZA_112233_Val.doc”, “_)(1)
End Sub
In business, you may find you often need data from a wide variety of cells on
your worksheets. Knowing how to access this data from different strings and
extract them if needed will prove invaluable to you when it comes to writing
reports and preparing proposals.
Being able to manipulate strings can simplify much of the work you would
normally have to do. Once you master these skills, you’ll find that you are
freeing up a great deal of time so that you can focus more on the purpose of
your business.

95
Chapter 3

96
How to Avoid Common
Mistakes in Excel VBA

There is a lot to learn in Excel VBA and it can easily overwhelm you if
you’re not careful. As a beginner, you may find that you will make more
mistakes than you would like to. Don’t worry about that, it is perfectly
normal however, there are a few tricks that can help you from venturing off
down the wrong path so you don’t have to back track and fix them.
It is true that we all learn from our mistakes but especially in the world of
business, mistakes can quite often prove costly. Learning how to use VBA is
like learning any other skill, which means that there is only so much you can
learn from a book, the rest must be acquired through practice. Remember,
nothing worth learning can be glossed over and rushed. So take your time and
practice these skills over and over again until they feel like second nature to
you. If you take the time to do this first, before you expose your newfound
skill to your business, you’ll have less chance of making those kinds of errors
that could prove costly.
Still, there are a number of common mistakes people make with VBA that are
definitely worth taking a closer look at. By being aware of these types of
mistakes you can use your practice sessions to figure out ways to work
around them so you are less likely to fall into those traps when you take your
new skills and apply them in real life.

Overusing .Select and .Activate


Select and Activate are two of the most common commands you use when
using a macro recorder. However, more often than not they are not even
necessary. In many cases, using them could prove to be quite redundant for
several reasons. So, if you don’t need this particular function then it’s a better
idea to delete those commands altogether. Once you do, you will see the code
improve, working faster than normal. However, if you feel you will need to
perform either of these two functions, it is a good idea to keep the commands
in place as it is a means of ensuring the code continues to function in the
correct way.

Overuse of the variant type


Sometimes new users of VBA can get the many variant types confused. You

97
may think that you are using one type when in actuality you are using a
totally different one. For example, using a Dim code such as “Dim d, e, f as
Long”. You might assume that this is a Long type variant. It’s a logical
conclusion and a mistake that many newbies actually make.
If you’ve made this mistake, don’t worry, you’re in good company. However,
only types “d”, and “e” would be variant types, meaning that they can be any
type and can be changed from one type to the other whenever needed.
Using this type of coding can be very tricky and confusing. Since using them
could create a lot of errors in the code that could be extremely difficult to find
later on. Because this is such an easy mistake to make, it may be a good idea
to avoid using Variant variables in the beginning. Once you become more
familiar with the other more basic forms of coding you can gradually ease
your head into the lion’s mouth and practice this more advanced form. It will
save you a lot of problems that will inevitably cause you frustration if you do.

Underuse of the Application.ScreenUpdating = False


Every time you make a change to a cell in your worksheet, Excel will go
through and update the screen. This will ensure that your new changes appear
as you make them. If you are working for an extended amount of time, you
could easily input a lot of data. Depending on the power of your computer
and the amount of data you’ve accumulated, it could lead to a lag time in the
system if it is not updated. To do this, you can always stop your work at some
point and do an update by following the code below:
Public Sub MakeCodeFaster()
Application.ScreendUpdating = False
‘do some stuff
‘Always remember to reset this setting back!
Application.ScreenUpdating = True
End Sub
While the system does automatically update the screen periodically. If the
data you’re working with is very important, it never hurts to add a manual
update to protect your work.

Adding a name of a worksheet to a string when it is not


necessary

98
It can be very tempting to write codes referencing the specific name of a
worksheet. It can be a means of ensuring that the program will access the
correct worksheet in a string. However, when working in VBA this is not
necessary. Consider this example:
Public Sub SheetReferenceExample()
Dim ws As Worksheet
Set ws = Sheets(“Sheet1”)
Debug.Print ws.Name
End Sub
While this type of mistake won’t yield you any negative impact, if you do not
break this habit, it may cause difficulties for others who try to use your
programs. For example, if you took your worksheet and gave it to someone
else who wanted to rename it, then it may no longer function as it should
because you’ve named the worksheet when it wasn’t necessary. So, in the
interest of camaraderie, it just makes sense that you try not to develop this
type of habit in the first place.
The best practice is to make sure that all of your references directly point to a
corresponding object and then allow the program to find the sheet. As long as
you have added the right code, you will see Sheet1 and not a series of sheets.

Failing to qualify range references


When working with VBA, beginners usually fail to qualify their range
references. This is a common error as many newbies are not really sure what
to look for. So, it is very important that you take extra care to ensure that you
qualify all references as soon as possible so you don’t get stalled later on.
If you’re unsure of either what a range reference is or you’re in doubt about
how to find them, here is are a few things to keep in mind that could help
you.
If the code is Range (A1) then you need to consider the exact worksheet it is
referring back to. Your answer to this problem will always refer to your
active sheet unless there is something else in the code that is referencing a
different page. As a rule of thumb, the ActiveSheet will always be the sheet
that is currently under review.
If you use Range() without specifying which worksheet to use, Excel will

99
automatically assume that you are referencing the active sheet. So, if you
want to reference a different sheet, you need to make sure that is added to
your code beforehand.

Sub functions that are too long


If you create a function and the result is longer than a single page of your
module then there is a good chance that it is too complicated or too long.
Long codes are not a problem in and of themselves but the more complex the
code is the more of a chance of error or of a code that lags and bogs down the
system. There are quite a few things you can do to prevent your code from
just going over the top. But one of the easiest ways to avoid this problem is to
pay extra attention to keeping the Sub and Function methods as lean as
possible. Make good use of any helper functions or any possible sub
procedures you can apply that will help you to do this.
It is inevitable that you will make mistakes and you learn this new skill but
those that take the time, practice, and pick up on these many tricks will
master it much faster than many others who just enjoy the experience of
diving right in.
We all know how complicated and confusing these things can be when you
are just learning how to use Excel VBA. No doubt, it will take an investment
in time to make sure you fully understand exactly how the module works and
what you have to do. If by some chance, you are having issues with the
coding, take the time to look up some of the more common problems that
others face and learn how they fixed them.

100
Chapter 4

101
Learning to Debug Your Program

No matter how good you are at writing code, it is inevitable that you will
have errors at some point in your program. You may think that everything is
perfect as you input your code but when you try to run it, either it won’t work
the way you planned or there is a glitch somewhere. The trick is to know how
to find where the problem lies so you can fix it.
Here, in this chapter, we will discuss some of the most common problems
that happen in a VBA code and give you some helpful tips on how to fix
them so you can get back to what you need to be doing.

Compile Errors
One of the most important things you should learn is how to handle macro
errors but this can be hard to do, especially if you haven’t identified what’s
wrong with your system. One of the easiest ways to learn how to navigate a
program so you can find the errors is to deliberately create an error so you
can understand what is happening within the program. It will give you
practice in taking the steps needed to locate the problem in a safe
environment.
So, let’s try this with a damaged code to see what happened.
X=4
Range(A1”.Value = X
If this is the actual code you are working with, when you attempt to active it,
you’ll immediately receive an error message notifying you that VBA is not
able to compile the code. This is because the code does not have a defined
relevant variable. You are missing some data and therefore the program
cannot continue. If you click on the OK button then you will be redirected
back to the code so you can fix it. If you need more information about the
error, you can click on the help button instead.
In this instance, the notification is letting you know that the variable for X is
not defined correctly because the Option Explicit statement is needed to start
the code. So, to fix the error you need to go back and declare all of the
variables to ensure that the program is working correctly.
It is important to keep in mind that if the VBA picks up an error in your

102
written code, it will show up on the screen in blue because it is constantly in a
debugging mode. The beauty of this system is that the internal alert will
notify you any time you are writing code with the wrong syntax so you can
fix it long before you get knee deep in code and have to work your way back
to the problem. By using it, the majority of errors will be caught in this way
and will be easy to fix. If you prefer, you can turn off the debugging process
at any time by clicking on the Rest option inside the VBA Editor.
The above listed problem is relatively easy to correct. All that is needed is to
add the missing data (Dim X As Integer) to the beginning of the code.
However, other problems will present much more complex errors to fix.

Fixing Functional or Logical Errors


Functional and logical errors happen when VBA fails to give you an error
message. Logical errors occur when the code is expecting one result but
instead receives another. You might successfully write a few lines of code
designed to make calculating the factorial of a user provided integer and
when you do a test run everything seems to be working fine. But, if there
happens to be a reason why one factorial is read incorrectly by the program it
would cause a logical error.
To fix this type of error you need to back track to the source of the problem.
The matter is easy when you get an error message but it becomes much more
complicated if you have no idea what the issue is. The good news is that the
VBA comes with its own built-in debugging system that will methodically
work its way through all of the functions in your written code, analyzing
them one at a time helping you to figure out what the root problem really is.
To do this, select each function of your code one at a time by clicking on F8.
As you have probably already gathered, there is a lot involved in learning
Excel VBA, much of it can seem overwhelming. As you search for books that
will break down all of the different lessons, it is quite common to have more
questions than answers. However, there is no reason for you to learn and
master everything in one fell swoop. In fact, if you just learn a few tips and
tricks along the way, you can not only impress your colleagues and friends
with your amazing abilities but you’ll build up your confidence as well while
you’re learning.
Under normal circumstances, if you assume that your code is correct you
should be able to see some data appear in the first two rows or columns of
your spreadsheet. If they are there, you want to take the following steps to fix

103
the errors.
• Start by clearing the range from A1 : E2
• Open up your VBA Editor
• Resize it so that you can see it and the current worksheet at the same
time
• Move your cursor over to the next line of code
• Press F8 again
One this is done the first line of your module will turn yellow. This is your
program telling you that there is a problem. Continue to press F8 until you
see another problem appear. As you do this, the Editor will enter various
numbers based on the specific parameters you set and the predetermined
number of rows and columns. When you hold your cursor over a variable you
will see its value. By continuing to press F8 you will begin to see where the
problem is and where you can fix it because the code will not be able to
execute its actions correctly.

Basic Problem Solving Tips


Finding errors can be really difficult to do but with a little practice and as you
become more familiar with proper coding language you will be able to sift
through these problems all on your own. Here are a few tips and tricks you
can try that can help you to find errors in your code and fix them.

Use your immediate window to find any strings that have


already been evaluated
It is very difficult to find strings that have already been evaluated. You could
stare at your screen for hours at a time searching for a small part that is out of
place. To simplify this process you can concatenate (or link) several strings
together. By using the Debug.Print statement along with a definition
statement your search will be much more efficient. Using this process will
allow you to be better able to seek out the line that needs to be evaluated in
your immediate window.
The Debug.Print statement can be very useful regardless of where you are in
the debugging process. The challenge though is that it is not a part of the
automatic system and you will have to set it up yourself. There are several
locations where you can add this command and let it do much of your work
for you.

104
• To verify previous arguments at the start of a new function
• To verify conditional values in your if…then statements
• When you need to track your loop value

Use data tips


Another effective resource is the use of data tips to view your variables.
When you are walking step-by-step through a section of code you can
determine the value of all the variables and properties. Keeping up with your
variables can be very helpful in answering the questions that may come up.
However, doing this one at a time is not always the most effective approach.
By activating data tips you can easily find if something within the code is not
automatically enabled. To do this:
• Select tools
• Select options
• Select Table Editor
• Look for the Code Setting heading
• Click on Auto Data Tips

Option Explicit Function


The Option Explicit function is very useful when you are looking to enhance
the efficiency of your code. It goes through the code eliminating the errors
before they become a problem. When this function is active, the option will
ensure that you always declare the type of variable you want to use. Even if
you misspell a variable, it will let you know so you can fix the issue before it
becomes an error.
While every module will not have this option, when you can it is very
beneficial to make sure that it is enabled in the VBE so that it can be accessed
whenever possible. To do this, follow these basic steps:
• From the Tools menu select Options
• Find the Editor tab find Code Settings
• Click on Require Variable Declaration
No matter what you are working on when it comes to writing code in VBA
there will inevitably come a time when you’ll hit a bump in the road. This is

105
especially true when you are just starting out. Whether you give the wrong
command or you simply transpose a few letters in a part of the code, you can
be sure that it will cause your program to come to a screeching halt until you
fix the problem.
While the options that we have listed here will not solve all of your problems,
they are a good place to start, teaching you little tricks and places to look to
find it. Learn these little strategies and rely on them. By doing so, you will
save yourself from many tedious hours staring at a screen trying to decipher
the problem. Of course, if you write short code like many of the examples
here in this book, you should be able to do this easily but rest assured, in
time, you will find a time when your work will become even more complex
and you will be happy that you have learned these tricks to help you suss it
all out.

106
Conclusion
Thank for making it through to the end of Excel VBA: Tips and Tricks to
Learn and Understand Excel Visual Basic Applications, let’s hope it was
informative and able to provide you with all of the tools you need to achieve
your goals whatever it may be.
Now, there is nothing standing in your way but to get some serious practice
in so that you become comfortable with using it. Learning a computer
language is like learning any other spoken language. It requires you to do
more than learn the words that make up sentences, you must also learn how a
computer processes your information and puts it to use.
This requires dedication and time. The good news though, is that if you’ve
already begun using Microsoft’s Excel, you are already on your way. Here, in
this book, we’ve tried to give you a good overview of VBA Basics and some
ways you can use it to enhance your business. Together, we have learned:
• VBA Basics: understanding how to use variables, loops, and other
common functions in VBA
• String manipulation and the many different ways they can help to ease
your workload
• How to find errors when your code doesn’t seem to work right
• Basic strategies in how to debug your system so that you can get back to
work
There is a lot more to learn about Excel VBA and no doubt you will go on to
do great things with this innovative program. We hope that we have given
you a solid footing to stand on that will give you an extra boost of confidence
that you can take further and use in a vast number of ways in the Excel VBA
world.
Finally, if you found this book useful in anyway, a review on Amazon is
always appreciated!

107
Excel VBA

Simple, Effective, and Advanced Strategies to


Execute Excel VBA
and Its Functions

108
Introduction
Congratulations on purchasing Excel VBA: Simple, Effective, and Advanced
Strategies to Execute Excel VBA and Its Functions and thank you for doing
so.
By now you’ve had a small taste of life with Microsoft’s Excel VBA, and
you’re likely looking for a little bit more. Most people, once they have
learned how much simpler life can be when they use VBA programming
language suddenly have minds flooded with immense possibilities that
require specialized skills and knowledge to master.
But when you start studying the available books on the topic, one can quickly
become discouraged. Many books assume that you know a certain level of
programming lingo and there are huge gaps in information that you struggle
to understand. It’s like you’re dealing with a world-famous chef who is more
than willing to give you his secret recipe but quietly holds back on the
primary ingredient that gives his dish the unique flavor and texture that
makes it special.
Here in this book, however, we take a completely different approach. Here,
you can learn VBA without fear of missing gaps of information. Even though
you’ve probably already worked some with Excel VBA, we assume nothing
and will walk you through the basics as if it were your first time. At the same
time, we try to give you some of those secret ingredients that will take you
from a beginner to a more polished user in the shortest amount of time
possible.
VBA is an incredible resource that can be utilized in all sorts of business
applications. With VBA, the ability to automate your reports and data is
made free and easy. Whether you’re looking to conduct surveys or use your
collected data in some other way, you’ll learn some easy tricks that will make
writing professional code quickly and efficiently one of the smartest moves
you can make.
Through the pages of this book, we will review the basic fundamentals of
learning Excel VBA by practicing some of the most commonly used codes.
From there, we will give you a better understanding of variables, statements,
loops and other functions.
Your approach to learning VBA will be different from one person to the next.

109
This book has been designed to take that fact into consideration. You may at
times feel the need to skip ahead if we are discussing a point you are already
familiar with, but we encourage you to go back from time to time to review
those fundamentals just the same. While you may already know these points,
it does help to refresh your mind with the fundamentals from time to time. It
can only serve to reinforce your knowledge as you move on to a more
advanced understanding of how to use this type of resource.
Together, we’re about to take an amazing tour in the world of VBA. We will
provide you with examples of codes you will be able to put to use
immediately. You will learn:
A Review of the Basics of VBA
How Your VBA Can Interact with Excel
Programming Tricks in Excel VBA
How to Manage Your Programming with Control Structures
What to do When You Have an Error in Programming
How to Use Call Functions and Subs
How Your VBA Programming Can Learn to Interact with Other
Programs
The methods we apply in this book are easy to use. They are the most
common for anyone looking to create professional applications. If you master
these, you will be able to expand your level of experience and apply them in
many other areas in computer programming. So, if you’re ready to use your
VBA skills and grow in your computer programming knowledge and skills,
then let’s get started right now!
There are plenty of books on this subject on the market, thanks again for
choosing this one! Every effort was made to ensure it is full of as much
useful information as possible, please enjoy!

110
Chapter 1

111
The Basic Structure of VBA

By now, we’ve all come to understand that at the very core of VBA are the
macros. Everything that is done in this type of program happens in the macro,
and without it, there is very little you can do. So if your plan is to create a
macro that can be self-edited, the very first thing you will have to do is to
master this skill above all others.
To do this, you will need to know the basic method of pulling up a Macros
dialog box, keying in a name for the macro you are creating, and then
clicking on the “Create” button.
This is a fundamental and one of the most basic steps in writing code with
VBA. Once you have created your macro, the VBA Editor will give you a
skeleton of a macro that will look something like this:
Sub HelloEverybody()
‘‘ HelloEverybody Macro

End Sub
You will notice in the above example that I’ve included several blank lines
that only have an apostrophe in them. These are the lines where you can key
in your comments. The VBA program ignores these marks as they mean
nothing to the system. So, you can use them freely when creating your code
to serve as space markers or reminders to be filled in later. On these lines,
you can write pretty much anything you want, and it won’t affect your code
in any way.
What you really need to pay attention to in the above example are the Sub
statements. Both the Sub and the End Sub statements are essential parts of the
VBA program because they mark the beginning and the end of a written
code. The initial Sub statement at the beginning of the code
Sub HelloEverybody()
Tells the program to start, and the final sub
End Sub
Is found at the end of every written code. Without it, the program will
continue to run expecting that there is more work to be done. So, in its most

112
basic form your beginning macro should be structured to look something like
this:
Sub name_of_macro()
An Algorithm
End Sub
If your code has to perform calculations then the basic structure should
follow this example:
Function name_of_function (parameter_1, parameter_2,
parameter_3…..paramenter_10)
Algorithm
End Sub
As you will learn, later on, every macro has the ability to access other
procedures or functions that you will express within your code. These will be
called upon by using a number of algorithms and functions, which we will be
discussing throughout the book.
These initial steps we’ve just gone through seem relatively simple, but there
are many small details that make them happen. These steps are very short but
learning them requires that you have at least a basic knowledge of writing
macros before we even get started. If not, we’ll take a few minutes to review
these basics before we get into the more meatier side of VBA.

How to Create a Procedure


To do any of these steps, it is important that you know exactly how to put
together a procedure in VBA. Every code that you write becomes a part of a
procedure so you need to know how to set up your VBA Editor, the location
where you will be writing all of your code. There are several ways to access
the Editor, but the easiest is to Press the Alt key and the F11 key at the same
time. This will place you right inside the Editor where you can do your work.
Now, we can begin to take steps to show you just how easy it can be to write
your first code. Let’s discuss each of the steps, one by one.
Step 1: Open a new workbook
This is where you will do all of your work in creating procedures and writing
code. All work done in the Editor is done in a workbook.
Step 2: Save the workbook before you start working

113
When you save the workbook, you need to assign it a name. Let’s use
MyWorkbook.xlsm for starters. When you begin working on different
projects, you can come up with other names that will work better for you.
Step 3: Open the VBA Editor
You can use the Alt+F11 key like we did earlier or you can do it by keying in
the following steps:
• Go to the Developer Ribbon
• Click on Controls
• Click on View Code
• Select View
• Select Project Explorer
A pane on the left side of your screen should now appear showing the name
of your workbook
MyWorkbook.xlsm
• Right-click on the pane
• Click in Insert and choose Module
• A blank page will appear
• Key in the following text:
• “Public Sub MyPractice”
• Press Enter
You have completed your first practice procedure. If you have followed the
steps correctly, you should see the following appear in your workbook
Public Sub MyPractice()
End Sub
Just to help you keep these things in order, remember the following:
• All modules are stored in workbooks
• All procedures are written in modules
• All code is written in procedures
• There are two different types of procedures

114
• Subs
• Functions
You can create as many modules or procedures you need to perform your
tasks. There are no limits to how many you can have so if you have a task
that requires many different procedures, you could create different modules
as needed to make sure they are organized and easy to manage.
The Power of the Sub Line
For starters, let’s focus our attention on what happens with the Sub line of
code. When you start writing your code, the Sub line is always the first. The
Sub line works in order, performing the task in the first line first, the second
line second, third line third, and so on. It will always continue in this form
until it has gone through every line of code you have written.
So, if you want to add comments to your code, it is important to use the
apostrophe symbol (‘). Following that, the remainder of the line will be
viewed by the system as a comment. You will see that when you do this, the
font will automatically turn green. This will allow you to write whatever you
want in the comment and the program will completely ignore it. Look at the
example below to see how this works:
Public Sub MyMessage()
‘ I am here but I have nothing to do’
‘The following line will tell the program what I want it to do for me’
MsgBox “This is my program”
End Sub
As you can see, when the program displays the result of this code, it will only
display the MsgBox coding “This is my program” and will completely skip
over the lines that start with an apostrophe so your message box will appear
as follows:
Public Sub MyMessage()
This is my program
End Sub
This way, you can include notes to yourself or other pertinent data that might
be related to your program right within the code without having to worry
about it messing up your code or affecting your procedure.

115
To run your procedure, however, you must follow some exact steps.
• Choose the Sub to Run
• Select the mouse inside
• Go to Debug and the select run from the menu (F5)
OR you can access it this way:
• Open your workbook
• Select the Developer Ribbon
• Go to Macros under the Code section
• Click on your Sub from the drop-down list
• Select Run
If for some reason it doesn’t work, and you receive an error message then
you’ll have to go back to your code to find the problem and resolve the issue.
Once you have completed all these steps, you can do a practice run of your
procedure to see if it works as you expected. It should display the message,
“This is my program” in the message box. If it appears correctly, click OK so
you can go back to the code to continue. At this point, you can either change
your message to something else, run the test again, or move on to the next
part of your code.

What to do When You Have Errors


Errors are inevitable when you are writing code. There is no way to avoid
them. However, rather than seeing this as a negative, look at it as a way to
perfect your code writing skills and see if you can learn something new from
the process.
Most errors are pretty easy to figure out though, as long as you know a few
little tricks on how to find out the problem. Below is a list of some of the
most common mistakes made in writing code in VBA that could easily be
fixed once you find them:
• There are spaces inadvertently left in a word
• Incomplete quotes, you may have one side but not the other
• Your forgot to add the parenthesis
• A spelling error in the command

116
• Non-alphanumeric characters used when writing variables, subs,
or functions
• Double naming, giving the same name to two different procedures
or variables
Whenever you are looking for a mistake or you receive an error message,
refer to this list first. In most cases, you’ll be able to solve the problem. If this
cheat sheet doesn’t work and you’re still trying to find your error, then your
next step is to refer to the Error Translator.
Using the Error Translator: To use the error translator, you need to have the
error message you received from the program and look it up on the list. In the
left-hand column of the page, you will see some of the common error
messages you might receive and the possible causes for them. On the right
side of the page, you will see examples of these errors and some suggestions
on how to correct them. For example, you might see something like this:
Error Possible Example
Message Causes Correction
By referring to
this sheet,
Ambiguous Two Subs have Public Sub Suggestion is to
name detected the same name DoStuff1() rename them or
which comes in
Public Sub number them so a PDF
DoStuff2() the program can downloadable
tell the difference
form you
Expected: end Equal sign Do While I = 5 Add the equal should be able
of statement missing from sign to the code
While to find the
Statement majority of
Expected: Do While Do While X<5 Add the missing your errors
expression statement expression without too
missing much hassle.
condition
Later in the
Expected: ) Parenthesis X = Jane(“Joe”) Make sure that book, we’ll go
missing you have both
sides of the into more detail
parenthesis about how to
find more
difficult coding problems that are not found on this sheet.

117
Chapter 2

118
The VBA Trinity

There are some pretty basic facts that you should know about Excel.
Remembering these fundamentals will make it easy for you to stay on point
when you’re writing code and not get confused.
First, nearly everything you do will be done in cells. Every cell belongs to a
worksheet somewhere, and finally, every worksheet is a part of a workbook.
This may seem like common sense, but these are really easy to forget.
Suppose you want to enter values for a particular program. In order for you to
do this, you must first look for the correct workbook. In that workbook, you
have to find the exact worksheet where the cells are located to write the code.
If you just randomly write the code on any page, it will not be able to access
the program when needed, and it won’t work, no matter how perfectly you
have written your code.
In VBA, you must tell the Editor exactly which Workbook and Worksheet
you want to access. These can be referred to as the VBA Trinity. They are 1)
the Workbook, 2) The Worksheet, and 3) The Range.
Since 95% of code writing will be found in one of these locations they
actually make up the core of Visual Basic Applications. Anything related to
VBA that is not contained in these three locations is most likely a tool
designed to help you to use them. Let’s look at these three elements a little
more closely.
The Workbook: The code you use to access the workbook is referred to as
the Workbook object. You will be able to use it to direct any tasks a
Workbook can do in Excel. Workbooks have many different properties, but
for the most part, you will only need to access a few to write code. Take a
close look at the example below to see how this works.
Public Sub ProjectName()
‘Show the name of the workbook
MsgBox Workbooks(“MyWorkbookVBA.xlsm”).Fullname
End Sub
Notice that there is a decimal located in the code right before Fullname. In
this case, the decimal simply means that what follows is a member of a
specific group of workbooks. Whenever you key in that decimal point, the

119
Editor will know to give you a list of properties that are related to whatever
object you’re working on at the time.
You can use this form of code to access any open workbook as in the
following example:
Workbooks(“<my workbook name here>”)
When you do this, make sure that you are only choosing an open workbook
or you will get an error message.
Another way you can access a workbook is to use a designated keyword like
ThisWorkbook. When you use this keyword, you will be referred to the actual
workbook that contains the code you are looking to access.
This method eliminates the need for you to have the exact file name of a
particular workbook. You can use this method whenever you are sure that the
code will not be affected if you change the filename or that copying the code
and adding it in another workbook is not going to require you to change the
code.
Because filenames will constantly change and you are likely to use the same
code repeatedly over different workbooks, these little tricks will definitely
work to your advantage. It will help to prevent your code from experiencing
problems every time you change a name.
A note of caution though. Make sure that you key in a ThisWorkbook name
rather than an ActiveWorkbook name, which refers to a workbook that is
currently active. Since any workbook can become active simply by clicking
on it, it is very easy to find yourself writing your code in the wrong one. By
using ThisWorkbook, you can avoid making this type of mistake altogether.
If you make it a habit to use ThisWorkbook when you are working in the
current workbook and use Workbooks(“<with the name of your workbook
here>”) when you are working on an open workbook, and ActiveWorkbook
only when necessary, and you are sure that is what you need, you are less
likely to have a problem that could increase the potential for error.

How to Use Your Worksheet


As a beginner with VBA, you worked with worksheets on a regular basis, but
now, you need to come to a better understanding of what they are and what
they can do. You already know that when you work in a worksheet, you are
entering data into cells. However, this is not the only function of a worksheet.

120
There are other functions of a worksheet that we will discuss in more detail a
little bit later. But right now, let’s learn a little more about the worksheet’s
primary function, that of accessing cells and using ranges.
Let’s say that you want to open a worksheet. You can do this by using the
name of the sheet you want to work on. For example, you might write a code
like the one below.
“Good Morning Everybody” in Cell A1 of Sheet1, Sheet2, and Sheet 3. In
code form, it may look like this:
Public Sub WriteToCell()
‘Write to cell A1 in Sheet1, Sheet2, and Sheet3
ThisWorkbook.Worksheets(“Sheet1”).Range(“A1”) = “Good
Morning Everybody”
ThisWorkbook.Worksheets(“Sheet2”).Range(“A1”) = “Good
Morning Everybody”
ThisWorkbook.Worksheets(“Sheet3”).Range(“A1”) = “Good
Morning Everybody”
End Sub
As you can see, you have identified the exact worksheet you want to work in
and instructed the program that you want the data entered in the A1 cell on
Sheets 1, 2, and 3.
To Hide or Unhide a Sheet: At times, you may want to hide a sheet from
view, or you may need to unhide one that has already been hidden. This may
be necessary when you want to prevent a user from having access to them.
You can hide any sheet in a workbook from view at any time, as long as at
least one sheet in the workbook remains visible. There are several ways to do
this.
• Using Menu Commands:
• Go to your Format menu
• Point to the Sheet you want to hide
• Click Hide
• Click on Unhide to bring the sheet back into view
• Click on OK to complete the action

121
Note: Since modules appear in the Visual Basic Editor, their sheets cannot be
hidden.
• Using Visual Basic Macro
Another way you can hide a sheet is in the Visual Basic macro. By writing it
into your code, you can not only hide the sheet but also prevent the Unhide
dialog box from appearing. In this type of case, there is only one way for the
sheet to become visible and that is by writing a new code into another Visual
Basic macro.
Code for hiding sheets with a Visual Basic Macro: xlVeryHidden
When you are writing this type of code, make sure that you are using the
Visible property to hide (or unhide) a sheet. By simply setting the Visible
property to True or False (or using the code above) you will get the same
effect as using the Hide or Unhide commands from the menu. Remember, if
you use the option to write the code, it will not only hide the sheet but also
the option from the menu bar. You will only be able to retrieve it by writing
another code to unhide it, so you don’t want to forget about the sheet or
where it is located.
Below is an example of how your code might be written:
Sub UnhideSheet()
Sheets (“Sheet3”).Visible = True
End Sub

Sub HideSheet()
Sheets (“Sheet3”).Visible = False
End Sub
Notice that when you want the sheet to be hidden, the result must be false,
but when you want it to be hidden, the result needs to be true.
You can perform the same action when you want to prevent a user from
changing the data on your sheet. By applying the same sample code with just
a little adjustment, you can protect or unprotect any sheet you are working
on.
Public Sub ProtectWorksheet()

122
MyWorkbook.Worksheets(“Sheet3”).Protect
Password:=“ThisPassword”
End Sub
Public Sub UnProtectWorksheet()
MyWorkbook.Worksheets(“Sheet3”).Unprotect Password:=“
ThisPassword”
End Sub
Note: These codes are based entirely on the name of the worksheet you are
working on. So, if for some reason, you decide later to change the name, the
code will no longer apply. For that reason, any time you write code like this,
if you create a new name for the workbook, you will also have to go back a
rewrite the code using the new name if you want the data to remain hidden or
protected.

Working With Ranges


You’ve probably also recognized that ranges are a very common part of
working in VBA. Whenever you are working with workbooks in any way,
you must remember to identify which one to use. The element Ranges is what
will be doing the bulk of the work. Ranges are used primarily to identify the
cells you need to use to perform whatever action of code you are working in.
Any action you are able to do in Excel, you can also do by using Range.
Cells are by far, the main component of Excel and VBA. Everything you do
starts and ends with cells. You can do three main things with cells.
1. You can read data in a cell
2. You can write to a cell
3. Or you can change the format of a cell.
There are several methods fo accessing cells, which can sometimes be
confusing. They all have similar functions but with slight variations.
Every worksheet has something called a Range property, which can be used
to access the cells in VBA. This Range property using the same basic
functions of an Excel Worksheet (“A1”, “A3:B7”), etc.
When you want to use the Range property to place a value in a cell, you can
write it using the following code as an example:

123
Public Sub WriteCodeToAccessCell()
‘ Write data to cell A1 in Sheet1 of this Workbook
ThisWorkbook.Worksheets(“Sheet1”).Range(“A1”) = 76
‘ Write number to cell A2 in Sheet1 of this Workbook
ThisWorkbook.Worksheets(“S/heet1”).Range(“A2”) = Jane D?oe
‘Write percentage to cell A3 in Sheet1 of this Workbook
ThisWorkbook.Worksheets(“Sheet1”).Range(“A3”) = 48%
End Sub
You will notice that the Range is simply a part of the worksheet, which is
actually a part of the Workbook. It follows the same basic hierarchy that
Excel uses so you should have no trouble grasping this concept. When you
want to use Range, you will always have to first identify the exact workbook
and worksheet it applies to.
You can also use the code name of a worksheet to specify which sheet
applies as in the following example:
Public Sub IdentifyingSheetName()
‘Write name to cell A1 in Sheet1 of this WorkBook
Sheet2.Range(“A1”) = 76
‘Write number to cell A2 in Sheet1 of this WorkBook
Sheet2.Range(“A2”) = “Jane Doe”
‘Write percentage to cell A3 of this WorkBook
Sheet2.Range(“A3”) = 56%
End Sub
The examples above, however, limit you to writing code to one single cell but
if you want to write to multiple cells, you can do this much faster using the
Range property. Notice the example below:
Public Sub WriteToMultipleCells()
‘Write number to multiple cells
Sheet1.Range(“A1:A20”) = 49

124
‘Write data to a multiple range of cells
Sheet1.Range(“B2:B15, B20:B25”) = “Susie Smith”
End Sub
There may be times when you’re not sure if using a Range is the best
decision when you write your code. There is a simple way to answer this
question. If you are planning to access the exact same cells every time the
macro runs and have the data placed in the same cell each time, then you
should use a Range.
For example, if the macro is expected to calculate a total of a number of cells
(A1:A100) and then write the sum in cell A101, then a Range makes more
sense than inputting all the cells one at a time.
You would use the cell property if you were only going to access a cell based
on a value that would constantly be fluctuating.
The Offset Property of Range: Ranges also have a property called Offset.
This refers to a specific count from its original position. Offsets are
frequently used when you have a Range of cells all of equal size and distance
from the current range. This can be very practical if you plan to choose a
Range based on very specific conditions. For example, you may be working
with a worksheet that has a column representing every day of the week and
need to write a certain value in a specific column. To make this clearer, let’s
examine the following example:
‘ This sub tests with different values’
Public Sub (TestValues()
‘Monday
SetValueSelect1, 15.21
‘Wednesday
SetValueSelect2, 123.45
‘Friday
SetValueSelect3, 485.23
‘Sunday
SetValueSelect4, 543.21

125
End Sub
‘Write the value to a column based on the day of the week
Public Sub SetValueSelect (1Day As Long, 1Value as Currency)
Select Case 1Day
Case1: Sheet1.Range(“F3”) = 1Value
Case2: Sheet1.Range(“G3”) = 1Value
Case3: Sheet1.Range(“H3”) = 1Value
Case4: Sheet1.Range(“I3”) = 1Value
Case5: Sheet1.Range(“J3”) = 1Value
End Select
End Sub
It is clear from this example that you would have to key in data for every
possible option without exception. This is how you would have to input the
code without using the Offset Property options. Let’s see the same code using
the Offset property.
‘ This sub tests with different values
Public Sub TestOffsetProperties()
DayOffset 1, 15.21
DayOffset 3, 123.45
DayOffset 5, 485.23
DayOffset 7, 543.21
End Sub
Public Sub DayOffset (1Day As Long, 1Value As Currency)
‘Use the value of day with the offset to identify the correct column
Sheet1.Range(“F3”).Offset(, 1Day) = 1Value
End Sub
Obviously, this solution has the much simpler code. If by chance the number
of days changes there is no need to add in any more code. Just remember that
whenever you use the Offset, there must always be some type of relationship

126
that exists between the different positions of the cells. If the columns were
random in any way then the use of the Offset would be of no value to you.

Using Rows and Columns as Ranges


Another way that Ranges can be used is when you want to use an entire Row
or Column to complete some action. By assigning the row or column you can
use to access a set parameter, you can apply the Range properties to simplify
the code.
Public Sub UseRowAndColumnAsRange()
‘Set the font size of column C to 11
Sheet1.Columns(3).Font.Size = 11
‘Set the width of columns G to K
Sheet1.Columns(“G:K”).ColumnWidth = 5
‘Set the font size of row 8 to 12
Sheet1.Rows(8).Font.Size = 12
End Sub
There are many ways you can simplify your code by using Range. It will
prevent you from having to key in every single cell into your code, saving
both time and reducing your chance of creating errors.
When it comes to Ranges, here are some key points you should keep in mind:
• A Range always refers to a range of cells
• You can read from one range of cells to another range of cells
• You can read values from Ranges to Arrays and from Arrays to Ranges
• You can use a For…Each for For loop to run through every cell within a
Range
• The properties for the rows and columns will allow you to access any
range of cells

127
Chapter 3

128
Understanding the Equals Symbol,
With, and Cell Functions

The Equals Symbol and What Does it Really Mean


Another common symbol you will use a lot of when writing code is the
equals (=) sign. The equal symbol is often used to place a set value within a
specific cell or variable. It is important to understand that the Equals function
is different from just giving the same value to two different properties.
Instead, it actually means something that is “assigned to” or something that
has “become” the same as.
Using “With”
We’ve already realized how Ranges can help to speed up our code writing by
helping us to avoid repetitive inputs that need to be keyed in. This type of
work can become extremely time-consuming as well as tedious. Another way
to save yourself from this type of drudgery is by using the “with” keyword.
Let’s start by looking at a sample code:
Public Sub UpdateCellsUsingWith()
‘ Using “with” means we only need to write
MyWorkbook.Worksheets(“Sheet1”) one time
With MyWorkbook.Worksheets(“Sheet1”)
‘ Writes the text “Hello Everybody” to cells A1:A5
.Range(“A1:A5”) = “Hello Everybody”
‘ Sets the font to blue
.Range(“A1:A5”).Font.Color = rgbBlue
‘ Sets the border to double line
.Range(“B2”).Borders.LineStyle = xlDouble
‘ Writes number to cell B1 and then changes format to currency
.Range(“B1”) = “36.49”
.Range(“B1”) =.NumberFormat = “$0.00”
End With

129
End Sub
If you study this example carefully, you’ll see just how much easier it will be
to write this type of code and read it using the “End With” marks as the final
component of the With section.
Take note of how the indented section of the code between the “With” and
the “End With” makes that section of the code stand out as distinctive from
the rest. This is a relatively common practice used in many programming
languages, especially when you are applying Loops or If statements to your
code.

Reading Code From a Cell


When writing to a cell, you are inputting specific values assigned to it.
However, there will be plenty of times when you will need to read from one
cell to another as well. Here is an example of how you might do this. The
Equals symbol can help you to determine which cells are read to and which
ones are read from. Look closely at the following example:
Public Sub ReadToFromDifferentCells()
With MyWorkbook.Worksheets(“Sheet1”)
‘Set A1 value to be the same as value in C1
.Range(“A1”) = .Range(“C1)
‘ Do Not Use - anything to the right of equals must be a single
cell
‘ The Value property of multiple cells is always blank so
A1:A5 is set to blank
.Range(“A1:A5”) = .Range(“C1:C5”)
End With
End Sub
In this example, you should note that anything used on the right side of the
Equals symbol is to be read from while anything to the left of the symbol is
to be read to. You are free to read from and write to as many sheets and
workbooks as you want as long as the workbook you’re using is currently
open. However, you can only use the With statement for one object at a time.
So, you can use it with a single workbook or worksheet, but when you are
working with multiple sheets, you will have to use another method to

130
accomplish your goal.
Now, let’s try to create a new worksheet using the Dim option. Here we are
about to create new names for the worksheets.
Public Sub UseNewWorksheetObjects()
‘ Declare worksheet objects
Dim writeNewSheet As Worksheet
Dim PaySheet As Worksheet
Dim AccountSheet As Worksheet
‘ Assign worksheet objects as worksheet
‘ Give the worksheet a new name
Set writeSheet = MyWorkbook.Worksheets(“Sheet3”)
Set PaySheet = MyWorkbook.Worksheets(“Payments”)
Set AccountSheet = MyWorkbook.Worksheets(“Account”)
‘ writeSheet the same as MyWorkbook.worksheets(“Sheet3”)
With writeSheet
‘ Set A1 value to be the same as A1 in sheet “Pay” of a workbook
called Others.xlsm
.Range(“A1”) = PaymentsSheet.Range(“A1”)
‘ Set A1 value to be the same as A1 in sheet “Account” of a
workbook called Others.xlsm
.Range(“A1”) = AccountSheet.Range(“A1”)
End With
‘When creating an object using the Set option, set the object to
Nothing when finished.
Set writeSheet = Nothing
Set PaySheet = Nothing
Set AccountSheet = Nothing
End Sub

131
As you can see, all the Dim and Set options are doing in this example is
renaming the worksheet. By doing this action, you can make it clear exactly
what the function of each sheet actually is. There are actually 3 different
methods for doing this.
First, when you need to use the same sheet several times, you might prefer to
give it a Full Name with a code similar to this:
MyWorkbook.Worksheets(“sheet3”).Range(“A1”)
Second, when you have to use the same sheet repeatedly for an
extended period of time, you can use the With…End statement:
With MyWorkbook.Worksheets(“sheet3”).
.Range(“A1”) =
End With
And finally, when you need to use many sheets repeatedly, you can use the
Worksheet Object:
Dim writeSheet As Worksheet
Set writeSheet = MyWorkbook.Worksheets(“sheet3”)
writeSheet.Range(“A1”)
It is a good idea to stop and practice this method a few times until you get the
hang of it. Don’t worry too much if it all comes at you in a jumble in the
beginning. As you get more comfortable with these methods, you will begin
to see the value of taking the time to master them.

Making Use of the Cells Property


All worksheets have a property referred to as Cells, which can be used in
much the same way as using a Range. However, there are a couple of
differences between the Cells property and the Range.
First, the Cells property is limited to using only a single cell at a time while it
can use a Row and a Column as arguments rather than a range.
Let’s compare the two differences before we go any further.
Public Sub UpdateCells1()
With MyWorkbook.Worksheets(“sheet1”)
‘ On both lines add the text “Sums” to cell A1

132
.Range(“A1”) = “Sums”
.Cells(1,1) = “Sums”

‘ On both lines write 52 to cell B10


.Range(“B10”) = 52
.Cels(10,2) = 52

‘ On both lines write 49.99 to range C2:C5


.Range(“C2:C5”) = 49.99
.Range(.Cells(2,3),Cells(5,3)) = 49.99
End With
End Sub
It may seem strange to have more than one way to do something, but it gives
you more options, which offers you more flexibility in your code writing. For
example, in the first line of this code, when you run the macro, the “Sums”
are placed in Cell A1. Most of the time this will be all you need, however,
there will be instances when you may not know exactly which cell the value
will be written to. So, using the Cells() option can be beneficial. This
function allows you to manipulate the details and select the right cell to use.
If you look at the last line of the example, we are also using both Range and
Cells together so that the end result is a range of cells using those numbers.
If by chance, you are attempting to access a cell based on a varying number,
using the alternative Cells property may be your best option. If we look
closely at the following example, this option becomes much easier to
understand. You will notice, that in the first row of the first column in the
code below, there is a blank cell:
Public Sub WriteInFirstBlankCell()
‘ Use data from last used column from the left
Dim 1LastCol As Long
1LastCol = cnSheet1.Range(“A1”).End(xlToRight).Column
‘ Write text to first blank cell in Row1

133
cnSheet1.Cells(1, 1LastCol + 1) = “Jane Doe”
End Sub
By studying this example, notice the number entered in the last column can
change based on any data included in other parts of the worksheet. If you
choose to use Range, you could convert the 1LastCol from a number to a
letter. For example, the fourth column could be changed to the letter D, and
the 27th column could be converted to the letters AA.
But, if you use the Cells property function, you could now have a row and a
column number and use them both to access a cell.Just keep these basic rules
in mind, and you won’t have any trouble deciding when to use Range or
Cells.
• You can use Range if the value of the cell will be consistent and not change
each time the macro runs
• Use Cells when the value within the cell changes

How to Copy and Paste Cells


Sometimes you may find that you need to copy and paste a large number of
sequential cells from one part of your worksheet to another. You may also
need to copy them to another worksheet altogether. Rather than re-key in all
of that data you could easily use the copy and paste feature with the
Destination argument or with the PasteSpecial function depending on what
you are really attempting to do.
Chances are, you’ve already copied and pasted many times in Excel. It is
probably one of the most commonly used operations in any Microsoft
program. But in most cases, this operation is done manually, which is
relatively easy to do if you don’t have to copy and paste a lot of data.
However, if you need to copy an extensive amount of data it suddenly
becomes time-consuming to move it in small pieces. But in VBA, you have
several options that can make this operation quick and painless.
All of the formulas we will use in this section assume that the workbook you
are referencing in your code is active and that the entire operation will be
completed within that active workbook. If your goal is to copy and paste into
a separate workbook, you can simply modify your references within the code
to the destination workbook you select. This will be much clearer in the
examples to follow.

134
Using the Copy Command in Excel’s Ribbon: Let’s start this function with
the simplest method, and that is to call on the Copy Command in Excel’s
Ribbon. Understanding this function can make it easier to understand how
VBA works when you are ready to do more extensive copying and pasting.
When you want to copy and paste into Excel, the function is very similar to
the copy and paste function in Word with a little difference. As you look at
your Ribbon on the top of your screen, you will notice the “Home” tab
located next to the “File” tab.
• Click on Home
• Select Copy from the menu

Notice that the “Copy” button is not just a simple click but is a split button. If
you click on “Copy”, you will be given two options in the drop-down menu.

The familiar Copy command is the most basic of all the copy functions and
the “Copy as Picture” command is probably less familiar, is used primarily to
copy a selected object in a picture format. To manually use these functions,
you simply click on the Range or Cells you want copied and click. However,
if you want these functions to be automated, you will need to use the VBA to
make it happen.
Keep in mind that the main purpose of using the Range.Copy VBA method is
to copy a particular range of Cells, columns, and rows automatically. If, you
were to copy a range manually, you could use the shortcut by pressing the

135
Control button (Ctrl) and the “C” key at the same time. The range of cells
you selected is copied and placed on the Clipboard. But the Range.Copy
function can do exactly the same thing in VBA. But, in VBA, you will have
an additional option to choose from.
When you use the “Destination” option, you can copy one range to another
range in addition to copying it to a clipboard. Let’s see how this works:
The basic syntax for this action should use the following example:
“ targetexpression.Copy(Destination)
Here, you will see that the “targetexpression” serves simply as a placeholder
for the Range variable that you need to copy and the “(Destination)” is the
only parameter that you will need. Of course, it is not necessary to have a
parameter but using one allows you to be very specific when identifying the
range that you want to copy. If you choose to omit the parameter, anything
you copy will simply be automatically placed on the Clipboard.
This means that the syntax you use will be dependent on your purpose:
• For copying a Range to the Clipboard, all you need to do is leave
out the Destination parameter is in the following example:
“targetexpression.Copy”
• For copying the Range to another location, simply specify the
Destination parameter in the code as in the following example:
“targetexpression.Copy(Destination)”
Now, let’s see if we can put this to the test. Before you begin, create a table
of data that you want to copy from. The table should include a list of certain
items labeled A, B, C, D, and E and at least 100 different requirements. It
could be a list of products to sell and an accompanying list of stores where
the merchandise is sold. Other things you can include in your chart could be
the price for each product, commission rates, etc.
Since this is only for the purpose of practicing, you can use data from a
worksheet you’ve already worked on, or simply copy it from some other
easily accessible source. Once, you’ve done this, you can practice copying all
of the data contained within your sample worksheet to the Clipboard. Try
using the following macro as a template:
Sub Copy_to_Clipboard()
Worksheets (“Sample Worksheet Data”) . Range (“B12:F52”) .Copy

136
End Sub
When you use this particular Sub, the procedure is based on the statement
below:
“ Worksheets(“Sample Worksheet
Data”).Range(“B12:F52”).Copy
To create this statement, you would need 2 different pieces of information:
• First, the Worksheet Range: “Worksheets(Sample Worksheet
Data”).Range(“B12:F52”)”
Sub Copy_to_Clipboard()
Worksheets (“Sample Worksheet Data”) .Range(“B12:F52”) . Copy
End Sub
This information identifies exactly what Range object needs to be copied. In
this specific case, the range consists of cells B12:F52 from the worksheet
labeled “Sample Worksheet Data.”
• Second, is the Copy function.
Sub Copy_to_Clipboard()
Worksheets (“Sample Worksheet Data”) .Range(B12:F52”) .Copy
End Sub
This particular syntax refers to the method used to create the copy.
You will see that once the macro is activated, the specified range of cells will
be surrounded by a dashed border that lets you know that the range is copied
and is ready to be pasted to another location.
Once the macro is activated, you can then go to the other worksheet and paste
the entire range manually with just a click of your cursor in the right place.
Finally, you can adjust the column widths so that all the data is visible within
each column and nothing is hidden.
This is a relatively easy method for copying and pasting, but it does have its
limitations. All it can do is copy the designated range to the clipboard and
nothing more. While you can create a macro to accomplish this task, you
don’t need one.
However, the Range.Copy method can go beyond the basics with the right
tools. It can also allow you to specify the destination where the range should

137
be pasted by using the Designation parameter:
Public Sub Copy_to_Range()
Worksheets(“Sample Worksheet Data”) .Range(“B12:F52”) .Copy _
Destination:=Worksheets (“Example B - Destination”) .Range (“B12:F52”)
Worksheets (“Example B - Destination”) .Columns (“B:F”) .AutoFit
End Sub
You should take note of the additional statement that uses the AutoFit
method that can be applied here. We’ll go through each line of this code so
that you fully understand exactly what’s involved in writing this type of code.
Line 1: Worksheets(“Sample Worksheet Data”) .Range(“B12:F52”) .Copy
This is the instruction that tells the program to copy the Range data to the
clipboard. It uses the Range.Copy method to copy the selected cells labeled
(“Sample Worksheet Data”)
Line 2: Destination:=Worksheets (“Example B - Destination”) .Range
(“B12:F52”)
This line gives you the Destination parameter for the data to be copied. It
specifies the exact range the data should be copied to. In this case, the
destination range is B12:F52 of the worksheet. If the destination to paste the
information is in another workbook, you simply need to qualify the reference
making clear where the final destination will be.
Line 3: Worksheets (“Example B - Destination”) .Columns (“B:F”) .AutoFit
This final line is actually optional and does not affect the actual outcome of
the copy and paste mechanism. Its sole purpose is to adjust the size of the
column the data will be pasted to so that all the contents will fit. In this
instance, the range must consist of 1 or more rows or columns.
Some may wonder why anyone would copy to the clipboard at all when you
can easily bypass the step and copy directly to a worksheet. While for the
most part, this is true, as you learn more about using VBA, you’ll find that
every copy and paste situation is not always as simple as the examples that
have been included here. As you get into more complicated forms of Excel
VBA, you’ll soon discover many cases where the Clipboard may be the best
destination for your copied data while you sort things out.

Using the VBA Method to Create a Range.Copy

138
If at all possible, when you can achieve your goals without using the
Clipboard it is usually best. By using the Range.Copy method to set your
Destination parameter, you avoid an additional step in the whole process.
This method is much more efficient and faster than the old method. Since
each time you use the Range.Copy method you are transferring data to the
Clipboard. To move the data from the Clipboard, you must use the
Worksheet.Paste method.
While the results you want to achieve are the same, using this method also
takes up space on your computer, which can eventually cause the whole
system to move much slower.
The Worksheet.Paste method: The Worksheet.Paste method is basically a tool
to extract data from the Clipboard and paste it into the target worksheet.
When you use the Range.Copy method without a target destination, all data
will be copied to the Clipboard until you use the Worksheet.Paste method to
extract it.
By studying the above examples, you should take note that the end result is
the destination and it looks the same in each case; the worksheet itself. So,
Excel basically copies all of the data including the values, formulas, formats,
etc. There is no specificity that would exclude copying anything that is within
the Range.
In many cases, this is exactly what you want, however, there will be times
when it is not exactly what you need. Look at the example below to see what
I mean:
Sub Copy_to_Range()
Worksheets (“Sample Worksheet Data”) .Range (“B12:F:52”)
.Copy_ Destination:=Worksheets(“Example B - Destination”) .Range
(“F52”)
Worksheets (“Example B - Destination”) .Columns(“B:M”)
.AutoFit
End Sub
Initially, this macro looks very similar to the ones above. However, if you
look closer, you’ll notice that the Destination parameter has changed. In this
code, the Copy_to_Range macro, the F52 cell of the destination range is now
where the pasting will happen.
When you run this macro, the worksheet above will paste the target range in
the new destination along with all related data and as you can see it will

139
create a problem in delivering the results you need.
The problem develops as a result of inconsistency. As long as the source cells
and the destination cells all have the same properties, this type of copy and
paste will go smoothly, but as soon as you create a code where the destination
cells have different values, your code will develop complications. For this
reason, you must take the necessary steps to ensure that the references used
always point to the right cell.
So, what can you do when the destination range cells change? Then, you
must stop and look at the formula used to calculate your results. In such
cases, you will need to depend on the Range.Copy method with a compatible
destination parameter. By using this method, you can copy the formulas
separately and paste them as values. This requires using the
Range.PasteSpecial method.

Using the Range.PasteSpecial Method


The Range.PasteSpecial method allows you to control what is copied within a
set destination range. Here, you will be given certain options contained
within the Paste Special dialog box.
This dialog box is what will allow you specify exactly what you want pasted
to the new destination. The basic syntax of this method is as follows:
“ target expression.PasteSpecial(Paste, Operation, SkipBlanks,
Transpose)
“target expression identifies the Range object and there are 4 different
options for PasteSpecial parameters.
• Paste
• Operation
• SkipBlanks
• Transpose
Each of these imitates the different options of the dialog box with one
exception; the Paste Link button found in the lower left corner of the box,
which we will discuss a little later on. For now, though, let’s take a look at
each of the parameters to see what they can do.
Paste: The Paste option allows you to specify exactly what you want to be
pasted in the destination range. With this option, you can choose to paste only

140
the formulas used in your target columns and rows, or you could choose to
paste only the data contained within it.
You’ll notice in the top left corner of the box, the selection for “all.” When
this option is chosen, it will blanket copy all of the data from the target form
and transfer it to the new destination but if you choose any of the values
below it; formulas, values, formats, comments, or validation, then it will
paste only those features in the new location.
The Paste parameter is equipped to use any of 12 different values in this
section. Look at some possible syntax examples below that you could also
apply when you are applying the PasteSpecial option:
‘ Copy and paste everything
.Range(“A1:C5”).Copy Destination:= .Range(“A20”)
.Range(“C15”).PasteSpecial xlPasteAll
If you need to only copy the formats for the formulas of worksheet then you
can use the following function:
‘ Copy and paste only formatting
.Range(“A1:C5”).Copy
.Range(“C15”).PasteSpecial xlPasteFormats
And when you only need to copy the values use this example for your
coding:
‘ Copy and paste only values
.Range(“A1:C5”).Copy
.Range(“D20”).PasteSpecial xlPasteValues
End With
End Sub
You can repeat this syntax with each of the different values on the Paste
Special dialog box so that you can be sure that you only copy and paste
exactly what you need.
Parameter #2: The Operation
When using the Operation parameter, you will be able to identify a specific
mathematical operation to be pasted in your destination calls. You’ll notice

141
this option in the middle of the dialog box directly underneath the paste
options we just discussed. This parameter can use any number of values
including the XlPasteSpecialOperation enumeration:
• xlPasteSpecialOperationNone - no calculations will be performed
while pasting
• xlPasteSpecialOperationAdd - all data copied will be added to the
values within the destination cells
• xlPasteSpecialOperationSubtract - all data to be pasted will be
subtract3ed from the value in the destination cell
• xlPasteSpecialOperationMultiply - all data to be pasted will be
multiplied with the values contained within the destination cells
• xlPasteSpecialOperationDivide - all data to be pasted will be
divided into the copied data
Parameter #3: SkipBlanks
The SkipBlanks option is used to specify whether any blank cells in the
copied range are to be pasted or not. This option is found just above the Paste
Link box on the dialogue box.
Here, you will use either a “True” or “False” option as follows.
If you want the blank cells to be pasted in the destination range, you will
mark the Skip Blanks as “True”. If you do not want them to be pasted, then
mark this option as “False”.
Parameter #4: Transpose
The Transpose option allows you to be very specific about the rows and
columns when you want to have their positions changed during pasting. You
can set this option to either “True” or “False”. If the option is “True”, the
rows and columns will actually switch places when they are pasted. If you
select “False” as the option, everything will be pasted exactly as it is when it
was initially copied.
The default value is always going to be “False” when using the Transpose
option. So, if you do not enter a “True” value, the Editor will keep everything
as is.

When You Want to Copy and Paste Links


Using the macro (Copy_Paste_Link) uses the Worksheet.Paste method where

142
you can actually paste links to your source data as you can see in the
following example:
Sub Copy_Paste_Link()
Worksheets (“Worksheet Sample Data”) .Range (“B12:F52”)
.Copy
Worksheets (“Example C - Paste Link”) .Activate
ActiveSheet .Range (“B12”) .Select
ActiveSheet.Paste _
Link:”True
Worksheets (“Example C - Paste Link”) .Columns (“B:F”)
.AutoFit
End Sub
As with all the other examples we have used, you will want to utilize the
Application.CutCopyMode property so you can cancel the Cut or Copy mode
whenever you need to. You can do this by adding the statement
“Application.CutCopyMode = False” at the very end of the Sub routine.
Let’s examine this function a little closer by analyzing each line of the code
above, so you understand how this macro is put together and how it differs
from others.
Line #1: Worksheets(“Sample Data”).Range(“B12:F52”).Copy
As in the other previous examples, this statement copies the set range of cells
to the Clipboard.
Line #2: Worksheets(“Example 4 - Paste”).Activate
This purpose of this statement is to activate the specific worksheet that
applies to this code.
To activate the Worksheet.Activate method us this expression.
“ expression.Activate
The term “expression” represents a variable of a specific Worksheet object.
In this example, “expression” is “Worksheets(“Example C - Paste Link”)”.
Line #3: ActiveSheet.Range(“B12”).Select
This purpose of this statement is to select the relevant range using the

143
following syntaxL
“ expression.Select
When this is used, “expression” becomes a variable that represents the Range
object. In the above example, that expression is “ActiveSheet.Range(“B12”).
Note that the first item that uses the expression “ActiveSheet” is actually an
Application.ActiveSheet property, which will return the active sheet in the
active workbook. The second time is used with (“Range (“B12”)”) refers to
the cell B12. So, in essence, the previous line of code was used to activate
this particular worksheet.
Lines #4 and #5: ActiveSheet.Paste Link:=True
It is important to understand that if you use the Destination parameter of the
Paste method, you cannot use the Link parameter. Therefore, when using the
Link parameter, the Destination parameter must be omitted and the
Worksheet.Paste method is used instead to paste the contents from the
Clipboard to the chosen destination.
So, because cell B12 of “Example C - Paste Link” worksheet is the current
selection, the items on the Clipboard are pasted there as well:
Sub Copy_Paste_Link()
Worksheets (“Worksheet Sample Data”) .Range (“B12:F52”) .Copy
Worksheets (“Example C - Paste Link”) .Activate
ActiveSheet . Range(“B12”) .Select
ActiveSheet .Paste _
Link:=True
Worksheets (“Example C - Paste Link”) .Columns(“B:F”) .AutoFit
End Sub
The above example shows how you can use the Worksheet.Paste method and
the Link parameter together, a method that allows you to paste the relevant
links to the appropriate data sources. This is all done by setting the Link
parameter to “True”.
There is a lot more involved in using the Copy/Paste method in Excel’s VBA.
Here, we’ve just covered the most commonly used methods, but if you expect
to be doing a lot of this when you are writing code, it is strongly

144
recommended that you continue to learn more about the different ways you
can copy and paste in VBA. Here, we’ve discussed both the Range.Copy
method and the Range.PasteSpecial method as well as how to copy links.
Keep in mind that you can always make adjustments in regards to your
source and destination cells when you want to copy and paste so you’re not
boxed in.
You’ve learned how to bypass the Clipboard, which will automatically lower
your risk of making mistakes or creating errors in your code that you will
have to go back and fix later. Because this information is so detailed, I
encourage you to create your own macros as practice solely for the purpose
of copying and pasting until you get the hang of it.

145
Chapter 4

146
Using Variables Rather Than Cells

When you are new to Excel VBA, the cell can mean everything. However, as
your work becomes more complex, you’ll find a great deal of convenience in
using variables rather than cells when you write code. It’s true, cells are very
versatile little creatures. They can hold a wide variety of data including text,
numbers, dates, and symbols. This is why we use them in our code as a
storage destination for temporary values. While there, we can perform any
number of calculations or mathematical operations.
You can also use cells to write values to a sheet. The problem that results,
however, is that when using individual cells, you will have to keep track of
every cell you use and the data you put in them. If you’re only working on 5
cells in a single column that may not be a problem but some worksheets may
have thousands upon thousands of cells, which will make this simple task
nearly impossible to do.
The way around this is to use variables instead. Simply create a variable and
let the VBA manage the worksheets for you. There are five different types of
variables you can use:
Long - an integer
Double - Decimal number
String - Text
Date - Date
Boolean - True or False
Variables in VBA are very similar to variables in Excel. You can name them
any way you like, but it is best to use names that will help you to recall the
particular code you are using.
Whenever you are using a variable, it must first be declared. There are five
main variable types you could use:
• Dim_Count As Long
• Dim TotalPrice As Double
• Dim CustomerName As String
• Dim ReportDate As Date

147
• Dim IsValid As Boolean
After you have chosen the variable that will work best for your task, you
must add something to it. For example:
_Count = 23
TotalPrice = 35.00
CustomerName = “John Doe”
ReportDate = #04/20/2018#
VBA has an internal function called “Convert and Coerce” to protect the
value. So, if you mistakenly place the value with the wrong variable type you
will create something called a “Type Mismatch” error, the program will
attempt to correct the problem and convert the variable to something that fits
better. If it cannot, then you will get an error message. It will look something
like the example below:
‘ When you run your macro and get a “Type Mismatch”
_Count = “35 ff”
TotalPrice= “Price.12.95”
It will attempt to convert the text into a number
VBA will attempt to convert the text to a number
_Count = “”55”
TotalPrice= “12.95”
If it cannot effectively convert the mismatch to a compatible format, you will
need to go back through the code and change it manually.
Now, let’s examine all the different ways you can use Variables:
Public Sub UseVariables()
You can create a variable using
Dim iRow As Long
You can give a value to a variable using
Row = 50
You can add more to the current variable by using

148
iRow + 5
You can perform a calculation within a variable by using
iRow = (5*10) / 25
You can use a function argument within a variable detailing which rows or
columns to use by using
MyWorkbook.Worksheets(“sheet1”).Cells(iRow,3) = 25
End Sub
As you can see, most of these variables are performing the same basic
function. They are evaluating everything that is to the right of the Equals
sign. Then they place the resulting value in the variable on the left side of the
Equals sign. Each time this is done, the current value to the left of the symbol
will be replaced by whatever it is determined the new value should be.
You can use the same basic principles found in this example and apply it to
the other forms of variables you can use.

149
Chapter 5

150
Beyond the Basics

Microsoft’s Excel VBA is a very much like an iceberg. No matter how basic
the function is, you will inevitably come across a more complex form of it
later on. So, when it comes to creating your own macros, there is much more
involved than what can readily meet the eye.
When building a macro, there are quite a few things you must keep in mind.
By following some of these basic rules, you can truly simplify your venture
into the macro world but at the same time, leave yourself open to learn new
things.
Rule #1: Keep it simple
It is one thing to write code in practice where you are free to make mistakes
and find the time to fix them. But when you are learning something new, it is
extremely important that you do a trial run of any macro you make before
you decide to launch it live. To that end make sure that your practice macro is
simple. So if you need to write code that will allow you to automate the
updates of a hundred worksheets your practice macro should be to update
one. If you need a macro to automate a hundred cells, then limit your practice
macro to update five.
By approaching your code in this way, it will be easier for you to catch errors
and modify it whenever needed. Once you have mastered the code and it is
working as you expect, you can always expand it to match your immediate
needs. Here is a sample of the order of getting a macro live.
1. Create your new workbook
2. Add some sample data
3. Build your new macro
4. Do a test run
5. Fix any errors
6. Create a copy
7. Add your code to your active workbook
8. Retest the macro with the new data
9. Fix any errors

151
10. Create a backup copy
11. Test your macro
12. Fix any errors
13. Go live
This may seem like a lot of repetitive busy work, but these rules are very
practical. Errors are a very real part of a programmers life, and you should
expect to have more than your share of them. It is much better though, to
have an error in a practice session than in a live code that could compromise
the data you have.
These steps are relatively easy to do and the more successful you are at it, the
more confidence you will have when you are creating macros in real life.
Never be afraid of making a mistake. Even if you can’t find the error having a
backup copy makes it possible for you to always go back to a safe place and
start again without risk of losing data.
Keep reading: There is a lot to know about using Excel VBA, and you will
likely remember those codes, syntaxes, functions, loops variables, arrays, etc.
that you use frequently, however, by making sure that you keep abreast of
what can be done with VBA you will be able to stay ahead of the game.
Keep a glossary of terms around until you can remember them all by heart.
There are many that you will have to rely on as you continue to grow in your
learning of VBA.
Rule #2: Always leave comments in your code. This will serve as a reminder
so that when you review it (perhaps months later), you know what your
intended purpose was.
Rule#3: Name your variables in a way that they will mean something to you.
This practice serves not just as a memory device, but it’s also protection. It
will keep you from mistakenly applying the wrong code to a particular
variable.
Rule #4: Whenever you see a code like
“MyWorkbooks.Worksheets(“Sheet1”), remember that it can be substituted
with the actual name of the worksheet itself.
Rule #5: Whenever you are working with large amounts of data first, copy
the values of the cells to an array. Then you will be able to manipulate them,
which will be a much faster process than trying to address each cell one at a
time.

152
Rule #6: When you write a new macro always create a copy of the workbook
first. This way, you reduce the risk of accidentally deleting the data.
Rule #7: For new macros, make sure you divide the task up into smaller bite-
sized pieces. Then, tackle each of them one at a time. Get the first one
working smoothly and then move onto the next one. Test each phase of the
code for errors before you begin working on the next piece of the puzzle.
Rule #8: Before starting a new project, turn on the OPTION EXPLICIT
button at the top of the module. When on, you are required to declare a
variable before you start work. To do this go to your menu bar and select
“Tool”, the “Options”, and then check the box for “Require Variable
Declaration”.
Rule #9: When creating a new macro start by setting up a few sample
products before you apply your new code with actual data. You can learn
many different details about writing code in VBA, but just like learning a
new language, the only way you can cement them in your mind is to create
and run macros in much the same way you would practice reading, writing,
and speaking in your new tongue. Whether you choose to create your sample
data for yourself or you want to test your new code with smaller projects, it is
a necessary part of life with VBA to test the waters first. By doing this, your
skills in VBA will improve much faster than if you just try to master it by
studying alone.
These are just a few basic guidelines you need to keep in mind when learning
VBA. While some of these rules seem pretty obvious, it is easy to forget
them when you are overwhelmed with work. No matter what your level of
skill is when it comes to VBA there is always room to learn more. By
following these basic guidelines, you are less likely to get sidetracked by
common errors that could zap your enthusiasm for writing code. You will be
able to stay focused and completely tuned to everything you are learning and
as a result, your ability to write code will be a more enjoyable experience in
the long run.

153
Conclusion
Thanks for making it through to the end of Excel VBA: Simple, Effective, and
Advanced Strategies to Execute Excel VBA and Its Functions, let’s hope it
was informative and able to provide you with all of the tools you need to
achieve your goals whatever it may be.
Mastering Excel VBA can be a challenge for the new person. The vast array
of functions that can be performed within in can literally boggle the
imagination. Even for those who are already adept at performing some basic
functions in Excel will find that at every stage there is always more to learn.
Here in these pages, we attempt to delve just a little deeper into the myriad of
uses found in Excel VBA. We have tried to give you tools that will make
your experience using this valuable tool more efficient in helping you to
complete pretty much anything you want to do.
VBA goes much further than Excel. It allows you to take everyday mundane
tasks and delegate them to a program that can perform those functions
automatically. Whether it is to calculate thousands of rows of inputted data or
to rearrange it in a way that is more beneficial to you, with the right code,
much of the work you’ve been doing manually can be passed on to the
program to do.
When you have mastered these simple techniques, you will find that your
work will be more professional, you’ll free up an immense amount of time,
and you’ll be free to tackle other projects. In fact, the more you know about
how VBA works, the happier you’ll be. You won’t have to struggle to
understand the complexities of a worksheet, you’ll be more organized, and
capable of doing amazing things.
We hope that you have gained valuable knowledge here in these pages but
also encourage you to continue to learn more about Excel VBA. There is a lot
more to learn, and you can only get better from here. Thanks for reading.
Finally, if you found this book useful in any way, a review on Amazon is
always appreciated!

154
Table of Contents
Excel VBA 7
A Comprehensive Beginner’s Guide to Learn and
7
Understand Excel Visual Basic Applications
Introduction 8
Chapter 1: What You Need to Get Started 10
Chapter 1: What You Need to Get Started 11
The Terminology 11
Understanding the Developer Window 13
Chapter 2: The Basics 16
Chapter 2: The Basics 17
Variable Basics 17
Dim VariableName As DataType 19
Understanding Variables 20
Chapter 3: Recording Your First Macro 26
Chapter 3: Recording Your First Macro 27
To Change Security Settings 27
Assigning a Macro 29
Relative References 30
Your First VBA Program 32
The Insert Form Button 33
Chapter 4: Understanding Arrays, Operators, and
35
Subroutines
Chapter 4: Understanding Arrays, Operators, and
36
Subroutines
The Two Dimensional Array (multidimensional arrays) 38
Operator Basics 40
Understanding Subroutines and Functions 41
Chapter 5: Decision Making Programming 44

155
Chapter 5: Decision Making Programming 45
Conditional Operators 45
Logical Operators 45
Chapter 6: Looping 50
Chapter 6: Looping 51
For…Next Loops 52
Start To End 53
Step 53
Statements 54
The For Each…Next Loop 55
Do While and Do Until Loops 57
Do While and Do Until Syntax #1 57
Do While and Do Until Syntax #2 57
While…Wend Loops 59
The Exit Statement and Nesting 60
Nesting 60
Conclusion 62
Excel VBA 64
Tips and Tricks to Learn and Understand Excel VBA for
64
Business Analysis
Introduction 65
Chapter 1: Visual Basic Applications - The Basics 67
Chapter 1: Visual Basic Applications - The Basics 68
Let’s Get Started 68
A Word About Macros 68
Understanding Variables 75
Numeric Data Types 78
Understanding Statements 79
Looping 81
Chapter 2: String Manipulation 85

156
Chapter 2: String Manipulation 86
Chapter 3: How to Avoid Common Mistakes in Excel VBA 96
Chapter 3: How to Avoid Common Mistakes in Excel VBA 97
Overusing .Select and .Activate 97
Overuse of the variant type 97
Underuse of the Application.ScreenUpdating = False 98
Adding a name of a worksheet to a string when it is not
98
necessary
Failing to qualify range references 99
Sub functions that are too long 100
Chapter 4: Learning to Debug Your Program 101
Chapter 4: Learning to Debug Your Program 102
Compile Errors 102
Fixing Functional or Logical Errors 103
Basic Problem Solving Tips 104
Use your immediate window to find any strings that have
104
already been evaluated
Use data tips 105
Option Explicit Function 105
Conclusion 107
Excel VBA 108
Simple, Effective, and Advanced Strategies to Execute
108
Excel VBA and Its Functions
Introduction 109
Chapter 1: The Basic Structure of VBA 111
Chapter 1: The Basic Structure of VBA 112
How to Create a Procedure 113
What to do When You Have Errors 116
Chapter 2: The VBA Trinity 118
Chapter 2: The VBA Trinity 119

157
How to Use Your Worksheet 120
Working With Ranges 123
Using Rows and Columns as Ranges 127
Chapter 3: Understanding the Equals Symbol, With, and
128
Cell Functions
Chapter 3: Understanding the Equals Symbol, With, and
129
Cell Functions
The Equals Symbol and What Does it Really Mean 129
Reading Code From a Cell 130
Making Use of the Cells Property 132
How to Copy and Paste Cells 134
Using the VBA Method to Create a Range.Copy 138
Using the Range.PasteSpecial Method 140
When You Want to Copy and Paste Links 142
Chapter 4: Using Variables Rather Than Cells 146
Chapter 4: Using Variables Rather Than Cells 147
Chapter 5: Beyond the Basics 150
Chapter 5: Beyond the Basics 151
Conclusion 154

158

You might also like