Professional Documents
Culture Documents
Application
Workbook
Worksheet
A macro is a series of commands and functions (function: A prewritten formula that takes a value or
values, performs an operation, and returns a value or values. Use functions to simplify and shorten
formulas on a worksheet, especially those that perform lengthy or complex calculations.) that are stored
in a Microsoft Visual Basic module (module: A collection of declarations, statements, and procedures
stored together as one named unit. There are two types of modules: standard modules and class
modules.) and can be run whenever you need to perform the task. If you perform a task repeatedly in
Microsoft Excel, you can automate the task with a macro. For example, if you often enter long text
strings in cells, you can create a macro to format those cells so that the text wraps.
A macro is a series of commands and functions. These commands and functions are written in a
programming language that is VBA.
VBA is not to be confused with Visual Basic, Visual Basic is a stand-alone program that runs
independently. VBA, on the other hand, is part of an Office application, and therefore cannot work
without the Office Application. For example, VBA for Excel is part of the Excel Program, and cannot run
without Excel. There are many similarities in the language constructs however, and as already stated
VBA is highly compatible with VB.
Visual Basic Script – a variant of the Visual Basic Language widely used for Internet Applications.
Microsoft Excel has a build-in macro recorder that translates your actions into VBA macro
commands. After you recorded the macro, you will be able to see the layout and syntax. Before you
record or write a macro, plan the steps and commands you want the macro to perform. Every action
that you take during the recording of the macro will be recorded - including the correction that you
made. (Exercise 1: Record a sample macro with few steps)
Need to provide:
a) Macro Name
How do we view the code for the macro or how do we open Visual Basic Editor?
Code Window
Module
Properties Window
Open/Double click on Module (which is there under VBA Project on left hand side)
Green: Comments (These lines do not get executed in the program, they just give some description
about the code. These lines start with ‘(single quote)).
What is a Module?
A module is a container for procedures. A procedure is a unit of code enclosed either between the Sub
and End Sub statement or between the Function and End Function statements.
If you start recording a macro, it will remember everything you do within a program. Macro will record
all the codes that are there in one category. (Exercise 2: Change the font name while recording macro
and check the code.)
Sub Macro1()
'
' Macro1 Macro
'
'
Range("A1").Select
With Selection.Font
.Name = "Arial"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
End Sub
Sub Macro1()
'
' Macro1 Macro
'
'
Range("A1").Select
With Selection.Font
.Name = "Arial"
End With
End Sub
1. F5 – Run Macro
2. F8 – Line by line execution (line will be highlighted in yellow color, you would be able to see the
result, once the line is executed)
3. F9 – Break Mode (You can pause/break the macro on a particular line to debug the code)
Types of Errors
There are 3 types of VBA error that you may encounter when executing your macro. These are
a) Compile Errors,
b) Runtime Errors
c) Logical Errors (or 'bugs').
Compile Errors
Compile Errors are recognized by the VBA compiler as being illegal and therefore, are highlighted as
errors before your macro even starts to run. If a compile error is an incorrectly formatted line of VBA
code, the VBA editor will immediately detect and highlight this, as soon as you attempt to move your
cursor away from the specific line of code. Alternatively, a compile error may be detected at the time
you attempt to run your macro (but before execution has started).
A compile error is generally easy to fix, as the VBA compiler will give you information on the nature of
this type of VBA error.
Runtime Errors
Runtime errors occur during the execution of your code, and cause the code to stop running. This type
of VBA error is also generally easy to fix, as you will be given details of the nature of the error, and
shown the location that is highlighted in yellow color where the code has stopped running.
Examples:
6 - Overflow (An overflow results when you attempt an assignment that exceeds the
limits/range of the assignment's target/variable. Example: Integer data type cannot handle
the values outside -32763 to +32673 hence we cannot assign any value outside the range.)
7 - Out of memory
9 - Subscript out of range (this error arises if you attempt to access elements of an array
outside of the defined array size – Example: if you define an array indexed from 1 to 10,
then attempt to access entry no. 11)
11 - Division by zero
13 - Type mismatch (this error arises when you attempt to assign the wrong type of value to a
variable – Example: define i as an integer, then attempt to assign the string "text" to i
Logical Errors
Logical Errors, otherwise known as 'bugs', occur during the execution of the VBA code, and allow the
code to continue to run to completion. However, the 'bug' may cause the macro to perform unexpected
actions or return an incorrect result. These errors are the most difficult to detect and fix, as there is no
way that the VBA compiler can identify and 'point to' the error, in the way that it does for compile and
runtime errors.
For example, you may accidentally code your macro to add together the wrong variables in a procedure.
The result would be incorrect, but the macro would usually continue to run to completion.
Worksheets(“sheet1”).Range(“A1”).Value = 3
Collections
A collection is an object that contains a group of related objects. Each object within the
collection is called an element of the collection. Collections are objects so have
associated methods and properties.
An example is the Sheets collection, which represents the worksheets in the active
workbook. This behaves a bit like an array, in that a specific worksheet in the collection
can be referenced using a numeric index:
Sheets(2).Activate
This makes the second worksheet active. Unlike a normal array, the index in a collection
object can be a name instead of a number:
Sheets(“Chart1”).Activate
When you want to work with a single object you usually return one member from the
collection. The property or method used to return the object is called an assessor. There are some
properties and methods that are unique to collections. The Count
property is one. It returns the number of elements in a collection.
Note: All instructions in VBA start with an Object and ends with a Property/Method
Property:
Method:
What is a Subroutine?
A Sub is a small chunk of code that you write to do a specific job. This starts with SUB
and ends with END SUB. You can run this Sub by pressing F5 in the VBA Editor, you
can run it by assigning the Sub to a button on a spreadsheet, and you can even run it
from the menu bar at the top of the Editor. In fact, there's quite a lot of different ways
you can run your Subs.
i. Macro
ii. Procedure
iii. Program
Subroutine playing
How to refer Excel Objects and their properties/methods? (Reference Styles in Excel Application)
1. Workbook Object:
a) ThisWorkbook : ThisWorkbook refers to the workbook where code is being written.
For example if we write: ThisWorkbook.Close, this closes the workbook where the
code has been written.
b) ActiveWorkbook: ActiveWorkbook refers to the workbook which is in active state
with active window. For example if we write: ActiveWorkbook.Close, this closes
the workbook which is in active status.
For example to refer the Value property & Delete Method for A1 Range object:
a) Activecell: : ActiveCell refers to the Cell which is in active state. We can find only one
activecell for a given line of code.
b) Activesheet: Activesheet refers to the Sheet which is in active state. We can find only one
activesheet for a given line of code.
c) Activeworkbook: Activeworkbook refers to the Workbook which is in active state. We can
find only one Activeworkbook for a given line of code.
ThisWorkbook refers to the workbook where code is being written while ActiveWorkbook refers to
the workbook which is in active state with active window. In case of only one workbook open,
ActiveWorkbook is same as ThisWorkbook.
Few examples are given below to copy/pass values from one range to another range:
a) Range(“A10”).Value= Range(“A1”).Value
Here Range(“A10”) is considered as destination reference and Range(“A1”) is source reference.
So, the value in A1 cell will be passed to A10 cell.
b) Sheets(“Sheet2”).Range(“A10”).Value= Sheets(“Sheet1”).Range(“A1”).Value
Here Sheet2 Range(“A10”) is considered as destination reference and Sheet 1 Range(“A1”) is
source reference. So, the value in Sheet1 A1 cell will be passed to Sheet 2 A10 cell.
c) ThisWorkbook.Sheets(2).Range(“A10”).Value= ThisWorkbook.Sheets(1).Range(“A1”).Value
Here Sheet2 Range(“A10”) is considered as destination reference and Sheet 1 Range(“A1”) is
source reference. So, the value in Sheet1 A1 cell will be passed to Sheet 2 A10 cell from
ThisWorkbook.
d) Workbooks(“2”).Sheets(2).Range(“A10”).Value= ThisWorkbook.Sheets(1).Range(“A1”).Value
Here WB Name 2, Sheet2 Range(“A10”) is considered as destination reference and
ThisWorkbook, Sheet 1 Range(“A1”) is source reference. So, the value in Sheet1 A1 cell will be
passed to Sheet 2 A10 cell.
Note: The same code can be used to pass the values of collection of cells. For example
Range(“E1:E10”).Value=Range(“A1:A10”).Value
Copy Style 1:
Range(“a1:a3”).copy
Range(“e5”).activate
Activesheet.Paste
Application.CutcopyMode=False
The above style is not effective. There is another way of doing effective copy & paste
Copy Style2:
Range(“a1:a3”).Copy Destination:=Range(“e5”)
Copy method has Destination argument. If we mention the range object in destination argument, then
the copied content will be pasted in the destination range.
VARIABLES
To use some values in code, you must first create them. The computer memory is made
of small storage areas used to hold the values of your application. When you use a value
in your code, the computer puts it in a storage area. When you need it, you let the
computer know. The machine "picks it up", brings it to you, and then you can use it as
you see fit.
In the world of computer programming, a variable is a value you ask the computer to temporarily
store in its memory while the program is running.
Declaring a Variable
When writing your code, you can use any variable just by specifying its name. When you
provide this name, the computer directly reserves an area in memory for it. Microsoft
Visual Basic allows you to directly use any name for a variable as you see fit. Fortunately,
to eliminate the possibility of confusion, you can first let Visual Basic know that you will be
using a variable.
In order to reserve that storage area, you have to let the computer know. Letting the
computer know is referred to as declaring the variable. To declare a variable, you start
with the Dim word, like this:
Dim
A variable must have a name. The name is written on the right side of the Dim word.
There are rules you should follow when naming your variables:
There are some words you should (must) not use to name your variables. Those words
are reserved for the VBA internal use. Therefore, those words are called keywords. Some
of them are:
Sub Exercise()
Dim Something
End Sub
This first line of code declares the variable (this is generally placed at the beginning of the
procedure).
Declaring these variables is not absolutely necessary, but it is recommended. It makes it easier to find
them, can help resolve problems, etc. In short, it's a good idea to get in the habit of declaring
variables correctly.
A variable's type indicates the nature of its contents (text, numbers, date, etc.).
Integer
Integer variables are used to store whole numbers.
Dim x As Integer
x=6
Range("A1").Value = x
String
String variables are used to store text.
Code:
Double
A variable of type Double is more accurate than a variable of type Integer and can also store
numbers after the comma.
Code:
Dim x As Integer
x = 5.5
MsgBox "value is " & x
But that is not the right value! We initialized the variable with value 5.5 and we get the value 6.
What we need is a variable of type Double.
Code:
Dim x As Double
x = 5.5
MsgBox "value is " & x
Note: Long variables have even larger capacity. Always use variables of the right type. As a result,
errors are easier to find and your code will run faster.
Boolean
Use a Boolean variable to hold the value True or False.
Code:
Variant Any type Any kind of data (default type if the variable is not declared).
The symbols in the table above can be used to shorten our variable declarations.
For reasons of readability, we will not be using these in the lessons, but here is an example anyway :
Sub Exercise()
Dim Something as String
Dim Whatever as Integer
End Sub
In the same way, you can declare as many variables as you want. Instead of declaring
each variable on its own line, you can declare more than one variable on the same line. To
do this, use one Dim keyword and separate the names of variables with commas. Here
are examples:
Sub Exercise()
Dim Father As String, Mother As String
Dim Some_Number As Integer, New_Number As Integer
End Sub
Notice that each line uses its own Dim keyword and every new line of declaration(s) must have a
Dim keyword.
The VBA Variant Data Type can hold any type of data: numbers , text or object variables.
At first it would seem that a VBA Variant data type is a great innovation: it provides a flexible
and versatile way of storing any type of data you want to throw at it. However the Variant
variable is a false friend and is the downfall of many new VBA programmer. It is easy to fall into
the VBA Variant trap but with a few simple changes your code can become faster, more
readable and more stable.
My advice: always declare variables using the VBA Dim statement and always specify a data
type that isn't a Variant. Many VBA code samples in books or on internet forums don't follow this
simple rule but all the sample code on SpreadSheetSuperStar.com follows this coding standard.
There are three reasons that using a VBA Variant is a very bad idea:
First, a variant data type allow VBA to select the underlying data type. A variant isn't really a
Swiss Army knife of variables. It is a wrapper for every other type of variable. VBA has to decide
if the variable you are assigning to the variant is a VBA text string, a numerical value like an
VBA integer, VBA double, VBA string or an object variable. Then it creates a integer, double,
string or object variable inside the variant data type container. This assessment takes time and
it takes additional memory to hold the information about the variable. So you are using more
computing power and memory. But that's not the worst part: the worst part is that sometimes
VBA assumes the wrong type of variable and that can cause problems.
When you specify a variable's data type it will avoid all this assessment and make your code
faster, more readable and more reliable.
OPTION EXPLICIT
We strongly recommend to use Option Explicit at the start of your Excel VBA code. Using Option Explicit
forces you to declare all your variables.
In order to ensure that you don't have any variables that start with the Dim keyword, you
can type Option Explicit at the very top of your coding window. What this does is to
instruct VBA to check your variables for you. Take the following code as an Example:
At the very top of the code we have Option Explicit. The Sub has one variable set up
with the Dim keyword - MyNumber. On the second line, we place a value of 1 in this
variable. On the third line, however, we have this:
MyNumbers = 2
So it's a good idea to type Option Explicit at the top of your code window in order to
prevent variables being set up accidentally
It is very important to find out the last row and last column of the data. Most of the times we would be
dealing with the data which is not static in terms of the dimensions (number of rows x number of
columns). There are many ways available to find out the last row or column. The best way of capturing
the last row & column number is below:
Last Row:
Sub Find_Last_Row()
Dim Data_LR as Long ‘Used Long Data type assuming that the number of rows are more than 32767.
‘If your data is less, then you can consider Data_LR as Integer
Data_LR=Cells(1048576,1).End(xlUp).Row
‘We might come across version related issues with this syntax as there is no 1048576th row in Excel
Version 2003.
Data_LR=Cells(Rows.Count,1).End(xlUp).Row
‘ Rows.Count returns the number of rows in the sheet. Using this syntax, we can avoid the version
related issues.
End Sub
Sub Find_Last_Column()
Dim Data_LC as Integer ‘ As there are only 16384 columns available and Integer can handle it
Data_LC=Cells(1, Columns.Count).End(xlToLeft).Column
End Sub
LOOPS
What is a Loop?
If, in your VBA program, you need to perform the same task (i.e. repeat the same block of code)
multiple times, this can be done using one of the VBA Loops.
1. For…. Next - Works with number range (Ex: 1 to 10, 200 to 450……)
2. For Each…. Next - Works with collection of objects (Ex: All worksheets in workbook…..)
3. Do While….. Loop - Woks with condition (Ex: As long as a variable value is less than 10….)
4. Do Until…. Loop - Woks with condition (Ex: Until a variable value becomes 10….)
Looping is one of the most powerful programming techniques. A loop in Excel VBA enables you to
loop through a range of cells with just a few codes lines.
Single Loop
You can use a single loop to loop through a one-dimensional range of cells.
Place a command button on your worksheet and add the following code lines:
Dim i As Integer
For i = 1 To 6
Cells(i, 1).Value = 100
Next i
Note: it is good practice to always indent (tab) the code between the words For and Next. This
makes your code easier to read.
Double Loop
You can use a double loop to loop through a two-dimensional range of cells.
Place a command button on your worksheet and add the following code lines:
For i = 1 To 6
For j = 1 To 2
Cells(i, j).Value = 100
Next j
Next i