MS Excel VBA v2
MS Excel VBA v2
Chapter 2 ..................................................................................................... 9
Introduction To Macro Programming .......................................................................... 9
What Is VBA? ........................................................................................................... 9
What Is A Macro? .................................................................................................. 10
What Is VBA Code? ................................................................................................ 10
What Is A Module? ................................................................................................ 11
What Are Procedures? ........................................................................................... 11
What Are Objects?................................................................................................. 12
What Are VBA Object Properties? .......................................................................... 13
What Are Object Methods In VBA? ........................................................................ 13
The Visual Basic Editor ............................................................................................... 14
Viewing The VBA Editor In Excel............................................................................. 14
Menu Bar ............................................................................................................... 15
Toolbar .................................................................................................................. 16
Project Window / Project Explorer ......................................................................... 17
Properties Window ................................................................................................ 18
Programming Window / Code Window .................................................................. 19
Immediate Window ............................................................................................... 19
Adding A VBA Module............................................................................................ 20
Microsoft Excel
Removing VBA Modules......................................................................................... 20
Object Browser ...................................................................................................... 22
Chapter 3 ................................................................................................... 24
Programming Basics .................................................................................................. 24
Workbook Object .................................................................................................. 24
Worksheet Object .................................................................................................. 24
Range Object ......................................................................................................... 26
Manipulating data ................................................................................................. 31
Using Message box ................................................................................................ 32
Using Input Box ..................................................................................................... 33
Debugging Errors ....................................................................................................... 34
Executing Code Line By Line ................................................................................... 34
Setting Up A Breakpoint......................................................................................... 35
Clearing A Breakpoint ............................................................................................ 35
Debug Mode .......................................................................................................... 36
Procedures ................................................................................................................ 37
Calling one procedure from another ...................................................................... 39
Chapter 4 ................................................................................................... 41
Defining Variables In VBA .......................................................................................... 41
What Is A VBA Variable .......................................................................................... 41
Why Use Variables? ............................................................................................... 41
Using Option Explicit .............................................................................................. 44
How To Declare A Variable .................................................................................... 48
Variables and data types ........................................................................................ 50
Variables and scope ............................................................................................... 54
Object Variables .................................................................................................... 55
Microsoft Excel
Chapter 5 ................................................................................................... 56
Using Loops ............................................................................................................... 56
Do...Loop Statements ............................................................................................ 56
For…Next Statements ............................................................................................ 57
For Each...Next Statements.................................................................................... 58
Speeding Up Loops ................................................................................................ 59
Chapter 6 ................................................................................................... 61
VBA IF Function ......................................................................................................... 61
Using a simple IF function in VBA ........................................................................... 61
Using a IF function with ELSE in VBA ...................................................................... 62
Using a IF function with ELSEIF and ELSE: in VBA .................................................... 63
Microsoft Excel
Preface
Recording Macros
The easiest way to learn is by recording a macro. Here users will learn the keys to
successful recording, running a macro, editing a macro and saving a macro enabled
workbook.
Programming Basics
Here, users will learn programming syntax to manipulate objects and it’s properties. Such
as copy and paste, entering text, numbers or formulas. How to trouble shoot macros.
VBA terminology Message & Input boxes
Working With Workbooks Debugging Errors
Working With Worksheets Executing Commands Line by Line
Working With Range Setting Up Breakpoints
Entering Data & Formulas
Using Variables
When it comes to VBA variables, poor coding practices can lead to potential problems
down the road. This section explains what are variables and how to define variables.
Understanding Variables Using Option Explicit
Why Use Varibles Variables & Data Types
Defining & Using Variables Using Object Variables
Scoping Of Variables
Using Loops
Users will learn how to execute a macro repeatedly using loops. Learn when to use the
right looping technique.
For Next Loops Looping With Unknown
For Each Loops Iterations
Looping With Specified Iterations Terminating Loops Early
Do Loops Speeding Up Loops
Decision Making
In this lesson, users will learn how to create macros that can make decision. Decision
making process is an important part of macro programming because it can help to solve
practical problems.
The IF Statement Using IF for Multiple Conditions
Using IF for Single Conditions
Microsoft Excel
Chapter 1
Recording Macros
The easiest way to create is macro is using the Macro Recorder. You do not need any
programming to do this. As long as you are performing the same things over and over
again, then the recorder will do just fine.
Executing A Macro
You can run the recorded macro from the Developer tab click Macros. Alternatively you
can use the keyboard shortcut ALT + F8.
From the macro dialog box, select the macro and click Run.
Editing A Macro
Let’s copy the recorded macro and paste it below. We will edit the copied version just in
case something goes wrong.
Change the macro name and delete the unnecessary codes and change the Color code to
65535 as shown below.
Sub MakeMeYellow()
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
While the shape is selected, type in a description so that users will know which macro will
be executed when the shape is clicked. To assign a macro to the shape, right click on the
shape, and click Assign Macro. In the Assign Macro dialog box, select the macro & click
OK.
To save the workbook as a macro enabled workbook, from the File tab click
Save & Send (or Export if Excel 2013) > Change File Type > Choose Macro-Enabled
Workbook > click Save As and give your file a name.
When you re-open a file containing macros, remember to enable macros otherwise the
macros could be disabled and you will not be able to run them.
Choose the option > Disable all macros with notification. When opening a workbook
containing macros, Excel will then prompt you on whether to allow the macros to run.
To allow the macros to run click “Enable content” if the prompt is above the formula bar.
If the prompt is in the middle of the screen, click “Enable macros”.
What Is VBA?
VBA stands for Visual Basic for Applications. Just like you and I have a language, computer
programs too have their own language. VBA happens to be the language in which Excel
speaks. For that matter, VBA is also the language of MS Word, PowerPoint, Access and
other MS Office applications.
The prospect of learning new languages scares us a lot. But worry not, VBA is much easier
to learn than French, Spanish, German or Chinese. The main reason why VBA is easy to
learn is because it almost looks like plain English.
For example the following line says hello to you:
MsgBox "hello"
You use a programming language, such as VBA, to communicate with a computer. More
particularly, you communicate instructions to the computer. Visual Basic for Applications
is the language that allows you and me to communicate instructions to Excel.
Just like any language, VBA too has its own rules, grammatical structures & nuances. Once
you understand these, speaking VBA with Excel becomes as easy as chatting with your
friend over a drink.
The use of terms such as sub procedure, routine, program, procedure and macro can be
a little bit confusing and, generally, they’re used interchangeably.
The basic VBE window can be divided in the following 6 sections, all of which I explain
below. In reality, there are more components than those which appear in this screenshot.
One thing you’ll notice when clicking on any menu, is that several commands have a
keyboard shortcut that is displayed at that point. Take a look, for example, at the Debug
menu and notice all the keyboard shortcuts that appear on the right side of this image.
The toolbar that appears in the screenshot above is called the Standard toolbar. This is
the only toolbar that the Visual Basic Editor displays by default.
You can change all of these settings by going to the View menu and selecting “Toolbars”.
The Visual Basic Editor displays a menu with the 4 different toolbars and the option to
access the Customize dialog.
This is the section of the Visual Basic Editor where you’ll be able to find every single Excel
workbook that is currently open. This includes add-ins and hidden workbooks. More
particularly, each Excel workbook or add-in that is open at the moment appears in the
Project Explorer as a separate project.
In the screenshot below, the only project that appears is the Excel workbook
“Book 1. xlsm”. Within the Microsoft Excel Objects node, you can see that the Excel
workbook has 2 worksheets. Finally, this particular project contains 1 VBA module and,
therefore, the Modules node is visible.
You can expand or contract the items that appear in the outline by double-clicking on
them or by clicking on the “+” or “-” that appear to the left of each item, depending on
the case.
Properties Window
The Properties Window (bottom left window) displays the properties of the object that is
currently selected in the Project Explorer and allows you to edit those properties.
There is a Code Window for every single object in a project. You can access the window
of a particular object by going to the Project Explorer and Double clicking on the object.
Immediate Window
The main purpose of the Immediate Window is to help you noticing errors, checking or
debugging VBA code. The Immediate Window is, by default, hidden.
Most of the times, the reason why you’re removing a VBA module is because you don’t
need the VBA code within it. In those cases, click “No” (there is no Un-Do if you change
your mind later on). If, for any reason, you actually want to export the module,
click on “Yes”.
Type in the Search Text Box the string that you want to use in your search. In the example
shown, worksheet is typed. Click the binoculars to search.
Method
Event
Properties
Creating a workbook
To create a workbook in Visual Basic, use the Add method. The following procedure
creates a workbook. Microsoft Excel automatically names the workbook BookN, where N
is the next available number. The new workbook becomes the active workbook.
Sub AddOne()
Workbooks.Add
End Sub
To save the workbook to the current path, you can add another line of code.
Sub AddOne()
Workbooks.Add
ActiveWorkbook.SaveAs Filename:="Allsales.xls"
End Sub
Opening a Workbook
When you open a workbook using the Open method, it becomes a member of the
Workbooks collection. The following procedure opens a workbook named MyBook.xls
located in the folder named MyFolder on drive C.
Sub OpenUp()
Workbooks.Open("C:\MyFolder\MyBook.xls")
End Sub
Worksheet Object
Resizing A Range
You can resize a current selection or an activecell using the Resize property. In the
example below the selection is resized to 5 rows and 3 columns.
ActiveCell.Resize(5, 3).Select
Example
Consider the spreadsheet below;
To select from A1 to E6, this is continuous data. You can use current region.
Range("a1").CurrentRegion.Select
This is useful to select continuous range of data. However if your data has empty rows or
columns, then you will need to select from A1 to the last cell used by Excel.
To select from A1 to E12, you will need to select until Excel’s last cell.
Range(Range("a1"), ActiveCell.SpecialCells(xlLastCell)).Select
Entering Values
To enter data in cell A1 in the active worksheet, we can use the following codes;
Range("a1") = 100
[a1] = 100
Cells(1, 1) = 100
ActiveCell = 100 (assuming the active cell is A1)
ActiveCell.Offset(0,-1) = 100 (assuming the active cell is B1)
Entering formulas
To enter a formula, we can use the Formula property. To enter a formula in cell B5 you
can use the following codes;
Range("b5").Formula = "=sum(B2:B4)"
ActiveCell.Formula = "=sum(" & ActiveCell.Offset(-3, 0).Resize(3, 1).Address & ")"
The second method assumes that the formula will be entered in the active cell and uses
the Address property. This method is better as it does not hard code any cell references.
The drawback is that the cell references are absolute ie =SUM($B$2:$B$4).
To make the cell references relative, consider the code below;
ActiveCell.Formula = "=sum(" & ActiveCell.Offset(-3, 0).Resize(3, 1).Address _
(rowabsolute:=False, columnabsolute:=False) & ")"
NOTE
RowAbsolute:=False removes the “$” for the rows
ColumnAbsolute:=False removes the “$” for the columns
We used the & operator to concatenate (join) two strings. Although Range("A1").value is
not a string, it works here.
The macro below will demonstrate what ever the user enters in the inputbox will be
displayed via the message box.
Sub GetName2()
UserName = InputBox("My name is David. what is your?")
MsgBox "Hello " & UserName
End Sub
This makes it easier to see what each line of code does. To execute the code line by line,
from the code window press “F8”. Each time F8 is pressed one line of code is executed.
Clearing A Breakpoint
A breakpoint in VBA is indicated by a red dot with a line of code highlighted in red.
To clear a breakpoint in Excel 2013, left-click on the red dot next to the line of code that
has the breakpoint.
Now, the breakpoint is cleared and the line of code should look normal again.
The part of code that COULD cause the problem is then highlighted in yellow.
If this is not the cause of the error, you will need to click the reset command to get out of
break mode. If there is an error in the code, correct the error.
Unlocking cells
When a worksheet is protected, you cannot make changes to any cells unless the cells are
unlocked.
Range("c2").Locked = False
Counting Worksheets
Knowing how many sheets you have will be useful if you need to cycle thru all the sheets
whether protecting sheets, getting data, or even unhiding hidden sheets. The code below,
displays the number of sheets in a message box.
MsgBox Worksheets.Count
Let’s imagine that you’re typing these statements and are currently at the following point:
Theoretically, you must type the whole name of the variable: “Variable_One”. However,
declaring the VBA variable previously allows you to take advantage of a keyboard
shortcut: “Ctrl + Space”. Once you’ve typed the first few (can be as little as 2 or 3) letters
of a declared variable name, you can press “Ctrl + Space” and the Visual Basic Editor does
one of the following:
As a general rule, the VBE completes the entry.
If there is more than 1 option available, the Visual Basic Editor displays a list of
possible matches to complete the entry.
In the case above, using the “Ctrl + Space” shortcut results in the Visual Basic Editor
displaying a list of possible matches to complete the entry as shown below.
Notice how the list above, in addition to Variable_One and Variable_Two, also includes
other reserved words and functions.
Declaring Variables Improves Code Readability, Makes Debugging Easier And Reduces
The Risk Of Certain Mistakes
whenever you declare VBA variables explicitly, you generally place all the variable
declarations at the beginning of a module or procedure. This improves the readability of
your VBA code.
Explicitly declaring all variables reduces the incidence of naming-conflict errors and
spelling mistakes. Naming-conflict errors are quite dangerous. If you don’t declare VBA
variables, there is a higher risk of accidentally over-writing or wiping out a pre-existing
variable when trying to create a new one.
Spelling mistakes can also create big problems. One of the main ways in which taking
measures to declare variables always helps you reduce spelling mistakes.
Variable declaration also helps reduce spelling mistakes by capitalizing all the lower-case
letters (in a variable name) that were capitalized at the point of the declaration.
To see how this works, let’s go back to the VBA code for the Variable_Test macro. Let’s
assume that you type the name of Variable_One without capitalizing (as shown below):
Once you’ve included the Option Explicit statement in a module, Visual Basic for
Applications doesn’t execute a procedure inside that module unless absolutely all the
variables within that procedure are declared. If you try to call such procedure, Excel
displays the following compile-time error message:
Notice, furthermore, how each of these variables appears 2 times after being declared:
Let’s assume that while writing the VBA code, you made a typo when writing the name of
the VBA variable Variable_One (you typed “Variable_Ome”). In such a case, the code of
the Variable_Test macro looks as follows:
The Visual Basic Editor should display the Editor tab of the Options dialog by default.
Otherwise, simply click on the relevant tab at the top of the dialog.
Within the Editor tab, you simply need to enable “Require Variable Declaration” by ticking
the box next to it. Then, click the OK button at the lower right corner of the dialog to
complete the operation.
Note that enabling Require Variable Declaration option only applies to modules created
in the future. In other words, Require Variable Declaration doesn’t insert the Option
Explicit statement in previously existing modules that were created while the option
wasn’t enabled.
Both variables are being declared as being of the Integer data type.
3 other keywords (in addition to Dim) may be used to declare a VBA variable explicitly:
Static.
Public.
Private.
The basic structure of the declaration statement is the same:
Keyword Variable_Name As Data_Type
“Keyword” is any of the above keywords: Dim, Static, Public or Private.
“Variable_Name” is the name you want to assign to the variable.
“Data_Type” makes reference to the data type of the variable. This element is
optional, but recommended.
The question of which is the exact keyword that you should use to declare a particular
VBA variable depends, mostly, on the scope and life you want that particular variable to
have.
The following table shows the relationship between the 4 different statements you can
use to declare a VBA variable and the 3 different scopes a variable can have:
Example
Excel will still allow us to run our code without using variables, it is not a must! But having
said this it is very bad programming to not use variables.
Let's use an example to highlight the above.
Sub NoVariable()
Range("A1").Value = Range("B2").Value
Range("A2").Value = Range("B2").Value * 2
Range("A3").Value = Range("B2").Value * 4
Range("B2").Value = Range("B2").Value * 5
End Sub
In the above code, Excel would need to retrieve the value from cell B2 five times. It would
also mean if we had many other procedures using the same value i.e B2, it would need to
retrieve it's value even more times. There is a lot of editing to be done if we were to
change from wanting B2 value to say, B5 value. It is messy code.
To declare a variable, use "Dim" followed by our chosen variable name then the word
"As" followed by the variable type. Let's now use a variable to store the value of cell B2!
Sub WithVariable()
Dim iMyValue as Integer
iMyValue = Range("B2").Value
Range("A1").Value = iMyValue
Range("A2").Value = iMyValue * 2
Range("A3").Value = iMyValue * 4
Range("B2").Value = iMyValue * 5
End Sub
In the above code Excel only needs to retrieve the value of cell B2 once. To edit our code
we only need to change it in one place. It is easier to read.
Therefore it is important to know what values you are expecting and declare using the
correct data type.
Procedure Scope
Procedure scope means that a variable is accessible (it can be read and modified) only
from within the procedure in which it is declared.
Sub StaticVariable()
Dim iMyValue as Integer
iMyValue = 10
Range("A1").Value = iMyValue
Range("A2").Value = iMyValue * 2
End Sub
Module Scope
Module scope means that a variable can be declared before and outside of any procedure
in a regular code module. If you use Private or Dim to declare the variable, only
procedures that are in the same module can access that variable. Since a module level
variable is not part of any procedure, it will retain its value even after the procedure that
changes its value has terminated. Module-level variables is declared at the top of the
module above the first procedure.
Private iMyValue As Integer
Sub PrivateVariable()
iMyValue = 10
Range("A1").Value = iMyValue
Range("A2").Value = iMyValue * 2
End Sub
Project Scope
Public variables have the broadest scope of all variables. A public variable is recognized
by every module in the active workbook. Project scope variables are those declared using
the Public keyword.
Public iMyValue As Integer
Sub PublicVariable()
iMyValue = 10
Range("A1").Value = iMyValue
Range("A2").Value = iMyValue * 2
End Sub
Do...Loop Statements
You can use Do...Loop statements to run a block of statements an indefinite number of
times. The statements are repeated either while a condition is True or until a condition
becomes True.
Tips: To stop an endless loop, press ESC or CTRL+BREAK.
Do…While repeats statements while a condition is true
Do…Until repeats statements until a condition becomes true
To Search a Dynamic List or a List with an Unknown Number of Rows
This code moves down column A to the end of the list and bolds cells with a value of
5 and above. (This code assumes that each cell in column A contains a value)
Sub DoUntilLoop()
Range("A2").Select
Do Until IsEmpty(ActiveCell)
If ActiveCell >= 5 Then ActiveCell.Font.Bold = True
ActiveCell.Offset(1, 0).Select
Loop
End Sub
For…Next Statements
You can use For...Next statements to repeat a block of statements a specific number of
times. For loops use a counter variable whose value is increased or decreased with each
repetition of the loop.
To Search a List with a Constant, Known Number of Rows
This code moves down column A to the end of the list and bolds cells with a value of
5 and above:
Sub ForLoop()
Dim x As Integer
NumRows = Range("A2", Range("A2").End(xldown)).Rows.Count
Range("A2").Select
For x = 1 To NumRows
If ActiveCell >= 5 Then ActiveCell.Font.Bold = True
ActiveCell.Offset(1, 0).Select
Next
End Sub
Alternatively you could give control to the user to decide the range of cells to run the
macro. This means the user will have to select the range first before running the macro.
Sub ForLoop2()
Dim x As Integer
NumRows = Selection.Rows.Count
For x = 1 To NumRows
If ActiveCell >= 5 Then ActiveCell.Font.Bold = True
ActiveCell.Offset(1, 0).Select
Next
End Sub
Sub UnProtectALL2()
For Each Worksheet In ActiveWorkbook.Sheets
Worksheet.Unprotect
Next
End Sub
Sub LowerCase()
Dim cell As Range
For Each cell In Selection.Cells
cell = LCase(cell)
Next
End Sub
Sub TitleCase()
Dim cell As Range
For Each cell In Selection.Cells
cell = Application.Proper(cell)
Next
End Sub
Speeding Up Loops
Loops should be avoided where possible as they can be pretty slow. Selecting ranges can
slow down a macro. Consider this macro running 15,000 times.
This is slow because this macro selects a cell 15,000 times & updates the screen each time
which causes the screen to flicker.
However if you want to retain the original macro and yet want it to run faster, consider
not updating the screen. This will avoid the flickering screen and speeds up the process.
Don’t forget to enable the screen updating after the complete process.
The ELSE statement may be supported by ELSEIF statements. They are typically used to
check for specific conditions and if all of them evaluate to FALSE, the steps specified in
the ELSE condition will finally get executed. The IF statement will check for a given
condition. If that condition turns out to be FALSE, the condition specified in the first ELSEIF
statement will be checked. If that also turns out to be FALSE, the condition specified in
the second ELSEIF statement will be checked, and so on and so forth. If all conditions
specified in the IF and ELSEIF statements turn out to be FALSE, by default the steps
mentioned under the final ELSE: block will get executed. Please remember that if there
are multiple ELSEIF statements, the first one that evaluates to TRUE will get executed and
once completed, the code execution will move to the END IF statement. Even if there are
multiple ELSEIF conditions that evaluate to TRUE, only the first one that evaluates to TRUE
Sub IF_ELSEIF_ELSE_FUNCTION()
If < <condition_1>> Then
MsgBox "1 is greater than 4"
ElseIf < <condition_2 if condition_1 = FALSE >> Then
MsgBox "2 is greater than 4"
ElseIf < <condition_3 if condition_2 = FALSE >> Then
MsgBox "3 is greater than 4"
Else < <If_Everything_Fails>>:
MsgBox "1, 2 or 3 are lesser than 4"
End If
End Sub
In the example shown below, the IF condition is checked first. Since it evaluates to FALSE,
the first ELSEIF condition is evaluated, followed by the second. Since none of them
evaluate to TRUE, the steps mentioned in the ELSE: condition are executed.
Sub IF_ELSEIF_ELSE_FUNCTION()
If 1 > 4 Then
MsgBox "1 is greater than 4"
ElseIf 2 > 4 Then
MsgBox "2 is greater than 4"
ElseIf 3 > 4 Then
MsgBox "3 is greater than 4"
Else:
MsgBox "1, 2 or 3 are lesser than 4"
End If
End Sub