Excel Macro
Excel Macro
Excel Macro
As humans, we are creatures of habit. There are certain things that we do on a daily basis every working day.
Wouldn't it be better if there were some magical way of pressing a single button and all of our routine
tasks are done? I can hear you say yes. In a nutshell, a macro is the magical single click button.
We will cover the following topics in this tutorial.
What is a macro?
The importance of macros in Excel
What is VBA in a layman's language?
Macro Basics
Step by step example of recording macros in Excel
What is a macro?
A macro is a piece of programming code that runs in Excel environment and helps automate routine tasks. In a
layman's language, a macro is a recording of your routine steps in Excel that you can replay using a
single button.
Macro Basics
Macros are one of the developer features. By default, the tab for developers is not displayed in excel. You
will need to display it via customize report
Macros can be used to compromise your system by attackers. By default, they are disabled in excel. If you need
to run macros, you will need to enable running macros and only run macros that you know come from a trusted
source
If you want to save macros, then you must save your workbook in a macro-enabled format *.xlsm
VBA Macro Excel Turotial (Jibran) Page 2
The macro name should not contain any spaces.
Always fill in the description of the macro when creating one. This will help you and others to understand what
the macro is doing.
Step 2) Select "Options" from the menu list as shown in screen shot below.
Step 3) Now another window will open, in that window do following things
Step 4) You will now be able to see the DEVELOPER tab in the ribbon
First, we will see how we can create a command button on the spreadsheet and execute the program.
Create a folder in drive C named Bank Receipts
Paste the receipts.csv file that you downloaded
Go to the local drive where you have stored the CSV file
Make the columns bold, add the grand total and use the SUM function to get the total amount.
Now that we have finished our routine work, we can click on stop recording macro button as shown in the
image below
What is VBA?
Why VBA?
Personal & business applications of VBA in excel
Visual Basic For Applications VBA basics
Step by step example of creating a simple EMI calculator in Excel
What is VBA?
VBA stands for Visual Basic for Applications. Before we go into further details, let's look at what computer
programming is in a layman's language. Assume you have a maid. If you want the maid to clean the house and
do the laundry. You tell her what to do using let's say English and she does the work for you. As you work with
a computer, you will want to perform certain tasks. Just like you told the maid to do the house chores, you can
also tell the computer to do the tasks for you.
The process of telling the computer what you want it to do for you is what is known as computer programming.
Just as you used English to tell the maid what to do, you can also use English like statements to tell the
computer what to do. The English like statements fall in the category of high level languages. VBA is a high
level language that you can use to bend excel to your all powerful will.
VBA is actually a sub set of Visual Basic 6.0 BASIC stands for Beginners All-Purpose Symbolic Instruction
Code.
Why VBA?
It uses English like statements to write instructions
Creating the user interface is like using a paint program. You just have to drag, drop and align the graphical user
interface controls.
Short learning curve. From day one that you start learning, you can immediately start writing simple programs.
Enhances the functionality of excel by allowing you to make excel behave the way you want it to
Variable – in high school we learnt about algebra. Find (x + 2y) where x = 1 and y = 3. In this expression, x and
y are variables. They can be assigned any numbers i.e. 1 and 3 respective as in this example. They can also be
changed to say 4 and 2 respectively. Variables in short are memory locations. As you work with VBA, you will be
required to declare variables too just like in algebra classes
Rules for creating variables
o Don't use reserved words – if you work as a student, you cannot use the title lecturer or principal. These
titles are reserved for the lecturers and the school authority. Reserved words are those words that have
special meaning in Vba and as such, you cannot use them as variable names.
o Variable names cannot contain spaces – you cannot define a variable named first number. You can use
firstNumber or first_number.
o Use descriptive names – it's very tempting to name a variable after yourself but avoid this. Use
descriptive names i.e. quantity, price, subtotal etc. this will make your VBA code easy to read
Arithmetic operators - The rules of Brackets of Division Multiplication Addition and Subtraction (BODMAS)
apply so remember to apply them when working with expressions that use multiple different arithmetic operators.
Just like in excel, you can use
o + for addition
o - for subtraction
o * for multiplication
o / for division.
Logical operators - The concept of logical operators covered in the earlier tutorials also apply when working with
VBA. These include
o If statements
o OR
o NOT
o AND
o TRUE
o FALSE
Now we will demonstrate how to program in VBA. All program in VBA has to start with "Sub" and end with
"End sub". Here the name is the name you want to assign to your program. While sub stands for a subroutine
which we will learn in the later part of the tutorial.
Sub name()
.
.
. End Sub
We will create a basic VBA program that displays an input box to ask for the user's name then display a
greeting message
This tutorial assumes you have completed the tutorial on Macros in excel and have enabled the DEVELOPER
tab in excel.
"Dim name as String" creates a variable called name. The variable will accept text, numeric and other characters
because we defined it as a string
"name = InputBox("Enter your name")" calls the built in function InputBox that displays a window with the
caption Enter your name. The entered name is then stored in the name variable.
"MsgBox "Hello " + name" calls the built in function MsgBox that display Hello and the entered name.
The above formula is complex and can be written in excel. The good news is excel already took care of the
above problem. You can use the PMT function to compute the above.
The PMT function works as follows
=PMT(rate,nper,pv)
HERE,
"rate" this is the monthly rate. It's the interest rate divided by the number of payments per year
"nper" it is the total number of payments. It's the loan term multiplied by number of payments per year
"pv" present value. It's the actual loan amount
HERE,
"Dim monthly_rate As Single,…" Dim is the keyword that is used to define variables in VBA, monthly_rate is
the variable name, Single is the data type that means the variable will accept number.
"monthly_rate = Range("B6").Value / Range("B5").Value" Range is the function used to access excel cells
from VBA, Range("B6").Value makes reference to the value in B6
"WorksheetFunction.Pmt(…)" WorksheetFunction is the function used to access all the functions in excel
Example 2
Step 1) Under Developer tab from the main menu, click on "Visual Basic" icon it will open your VBA editor.
Step 2) It will open a VBA editor, from where you can select the Excel sheet where you want to run the code.
To open VBA editor double click on the worksheet.
Step 3) In this step we going to see our fist VBA program. To read and display our program we need an object.
In VBA that object or medium in a MsgBox.
Step 4) In next step you have to run this code by clicking on the green run button on top of the editor menu.
Step 5) When you run the code, another window will pops out. Here you have to select the sheet where you
want to display the program and click on "Run" button
Summary
VBA stands for Visual Basic for Application. It's a sub component of visual basic programming language that
you can use to create applications in excel. With VBA, you can still take advantage of the powerful features of
excel and use them in VBA.
CHAPTER -3
Excel VBA Variables, Data Types & Constant
Variables are used in almost all computer program and VBA is no different. It's a good practice to declare a
variable at the beginning of the procedure. It is not necessary, but it helps to identify the nature of the content
(text, data, numbers, etc.)
In this tutorial, you will learn-
VBA Variables
Variables are specific values that are stored in a computer memory or storage system. Later, you can use that
value in code and execute. The computer will fetch that value from the system and show in the output. Each
variable must be given a name.
To name the variable in VBA, you need to follow the following rules.
Here are some example for Valid and Invalid names for variables in VBA.
My_Watch My.Watch
NewCar1 1_NewCar (not begin with number)
EmployeeID Employee ID ( Space not allowed)
In VBA, we need to declare the variables before using them by assigning names and data type.
In VBA, Variables are either declared Implicitly or Explicitly.
VBA variable is no different than other programming languages. To declare a variable in VBA you use the
keyword "Dim."
Syntax for VBA Variable,
To declare a variable in VBA, type Dim followed by a name:
Sub Exercise ()
Dim <name>
End Sub
Before we execute the variables we have to record a macro in Excel. To record a macro do the following -
Step 1): Record the Macro 1
Step 2) : Stop Macro 1
Step 3): Open the Macro editor, enter the code for variable in the Macro1
VBA Macro Excel Turotial (Jibran) Page 21
Step 4): Execute the code for Macro 1
Example, for VBA Variable
Sub Macro1()
Dim Num As Integer
Num = 99
MsgBox " Guru " & Num
End Sub
When you run this code, you will get the following output in your sheet.
In VBA, if the data type is not specified, it will automatically declare the variable as a Variant.
Let see an example, on how to declare variables in VBA. In this example, we will declare three types of
variables string, joining date and currency.
Step 1) Like, in the previous tutorial, we will insert the commandButton1 in our Excel sheet.
Step 2) In next step, right-click on the button and select View code. It will open the code window as shown
below.
Step 5) After turning off the design mode, you will click on commandButton1. It will show the following
variable as an output for the range we declared in code.
Name
Joining Date
Income in curreny
You can either specify the scope as private by default or public. For example,
Public Const DaysInYear=365
Private Const Workdays=250
Download Excel containing above code
Summary:
Variables are specific values that are stored in a computer memory or storage system.
You can use "Dim" keyword in syntax to declare variable explicitly
VBA data types can be segregated into two types
o Numeric Data Types
o Non-numeric Data Types
In VBA, if the data type is not specified. It will automatically declare the variable as a Variant
Constant is like a variable, but you cannot modify it. To declare a constant in VBA you use keyword Const.
1. Group logically related data together – let's say you want to store a list of students. You can use a single array
variable that has separate locations for student categories i.e. kinder garden, primary, secondary, high school, etc.
2. Arrays make it easy to write maintainable code. For the same logically related data, it allows you to define a
single variable, instead of defining more than one variable.
3. Better performance – once an array has been defined, it is faster to retrieve, sort, and modify data.
Types of arrays
VBA supports two types of arrays namely;
Static – These types of arrays have a fixed pre-determined number of elements that can be stored. One cannot
change the size of the data type of a Static Array. These are useful when you want to work with known entities
such as the number of days in a week, gender, etc.
Dynamic – These types of arrays do not have a fixed pre-determined number of elements that can be stored.
These are useful when working with entities that you cannot predetermine the number.
HERE,
Code Action
Dim arrayName (n) 1. It declares an array variable called arrayName with a size of n and datatype. Size refers to
datatype the number of elements that the array can store.
Dynamic arrays
The syntax for declaring DYNAMIC arrays is as follows:
HERE,
Code Action
Dim arrayName () 1. It declares an array variable called arrayName without specifying the number of
datatype elements
ReDim arrayName(4) 2. It specifies the array size after the array has been defined.
Array Dimensions
An array can be one dimension, two dimensions or multidimensional.
One dimension: In this dimension, the array uses only one index. For example, a number of people of each age.
Two dimensions: In this dimension, the array uses two indexes. For example, a number of students in each class.
It requires number of classes and student number in each class
Multi-dimension: In this dimension, the array uses more than two indexes. For example, temperatures during the
daytime. ( 30, 40, 20).
Create a new Microsoft Excel workbook and save it as Excel Macro-Enabled Workbook (*.xlsm)
Add a command button to the workbook
Set the name and caption properties of the command button
Write the code that populates the Excel sheet
Drinks(1) = "Pepsi"
Drinks(2) = "Coke"
Drinks(3) = "Fanta"
Drinks(4) = "Juice"
HERE,
Code Action
It declares an array variable called Drinks. The first array index is 1 and the
Dim Drinks(1 To 4) As String
last array index is 4.
Assigns the value Pepsi to the first array element. The other similar code does
Drinks(1) = "Pepsi"
the same for the other elements in the array.
Writes the value My Favorite Beverages in cell address A1. Sheet1 makes
Sheet1.Cells(1, 1).Value =
reference to the sheet, and Cells(1,1) makes reference to row number 1 and
"My Favorite Beverages."
column 1 (B)
Sheet1.Cells(2, 1).Value = Writes the value of the array element with index 1 to row number two of
Drinks(1) column 1
Summary
We will now add a command button to our workbook, for that we have to
We will now set the caption of the button to something more descriptive
Set the name property to btnButton. The name property is used to identify the control in the code window. btn is
the prefix for the button.
Set the Caption property to Click Me. The text in the caption property is what the users will see on the button.
Step 3) Then right click on the command button and select option "View Code".
Step 5) In next step, save code file and then exit the editor. To return to the Excel file click the Excel sheet icon
on the extreme left.
Step 7) When design mode is off, there will be no green highlight on it. Now you can Click on the command
button.
Prerequisite
Configure Microsoft Excel
As we see in previous tutorial, make sure your ribbon will have "Developer" icon as shown here.
VBA Arithmetic Operators are used to perform arithmetic operations such as adding, subtracting, dividing or
multiplying numbers.
The following table shows the arithmetic operators in VBA
Add a button to the Excel sheet as we show earlier, and then follow the following points
Enter the following code in between Private Sub btnAdd_Click() and End Sub
If the button is in active state (green background colour), then it's in design mode. You cannot execute code in
this state. If it is not in the active state (white background color), then it allows you to run the code.
Click on Design Mode button
The button should now appear as follows
The best way to learn is by practicing. Follow the above steps to create buttons for subtraction, division,
multiplication and exponentiation.
Write the code for the buttons and test them to see if the code executes.
Characters (Jul)
Symbol (-)
Numbers (2015)
String operators are used to manipulate string data. For example, you can concatenate the value of July-2015
from the first 3 letters of the month and the year like "Jul-2015".
The following table shows the concatenation string operator.
If 2 = 1 Then
MsgBox "True", vbOKOnly, "Equal Operator"
Else
MsgBox "False", vbOKOnly, "Equal Operator"
End If
HERE,
"If 2 = 1 Then… Else… End If" uses the if statement to evaluate the condition "2 = 1"
Logical Operators
Let's say you want to process a customer order. For that, you want to first check to see if the ordered product
exists or not. If it does, you also want to check if the quantity on hand is enough. Logical operators come in
handy in such cases. Logical operators are used to evaluate more than one condition.
The following table shows the properties that you need to change and the values that you need to update too.
HERE,
"If (1 = 1) And (0 = 0) Then" the if statement uses the AND logical operator to combine two conditions (1 = 1)
And (0 = 0). If both conditions are true, the code above 'Else' keyword is executed. If both conditions are not true,
the code below 'Else' keyword is executed.
HERE,
"If (1 = 1) Or (5 = 0) Then" the if statement uses the OR logical operator to combine two conditions (1 = 1) And
(5 = 0). If any of the conditions is true, the code above Else keyword is executed. If both conditions are false, the
code below Else keyword is executed.
HERE,
What is Subroutine?
A subroutine is a piece of code that performs a specific task and does not return a result. Subroutines are used to
break down large pieces code into small manageable parts.
Let's say you have created a user interface with text boxes for accepting user input data. You can create a
subroutine that clears the contents of the text boxes. A subroutine is appropriate in such a scenario because you
do not want to return any results.
In this tutorial, you will learn-
You will need to enable the Developer tab in Excel to follow along with this example. If you do not know how
to enable the Developer tab then read the tutorial on VBA Operators
The following subroutine accepts the first and last name and displays them in a message box.
Now we are going to program and execute this whole process for the subroutine. Let see this.
Sub-routines demonstrated with Example:
1. Design the user interface and set the properties for the user controls.
2. Add the subroutine
3. Write the click event code for the command button that calls the subroutine
4. Test the application
Step 3) Call the subroutine from the command button click event.
Right click on the command button as shown in the image below. Select View Code.
The code editor will open
Summary:
A subroutine is a piece of code that performs a specific task. A subroutine does not return a value after execution
Subroutines offer code reusability
Subroutines help break down large chunks of code into small manageable code.
What is a Function?
A function is a piece of code that performs a specific task and returns a result. Functions are mostly used to
carry out repetitive tasks such as formatting data for output, performing calculations, etc.
Suppose you are developing a program that calculates interest on a loan. You can create a function that accepts
the loan amount and the payback period. The function can then use the loan amount and payback period to
calculate the interest and return the value.
Why use functions
The advantages of using functions are the same as the ones in the above section on why use subroutines.
Rules of naming functions
The rules for naming functions as the same as the ones in the above section on rules for naming subroutines.
Code Action
"MsgBox It calls the function addNumbers and passes in 2 and 3 as the parameters. The function
addNumbers(2,3)" returns the sum of the two numbers five (5)
Step 4) Run the program, you will get the following results
Summary:
A single cell
A row or a column of cells
A selection of cells
A 3-D range
As we discussed in our previous tutorial, that VBA is used to record and run Macro. But how VBA identify
what data from the sheet needs to be executed. This is where VBA Range Objects is useful.
In this tutorial, you will learn-
Object Qualifier: This is used for referencing the object. It specifies the workbook or worksheet you are referring
to.
VBA follow object hierarchy pattern to refer object in Excel. You have to follow the following structure.
Remember the .dot overhere connects the object at each of the different levels.
Application.Workbooks.Worksheets.Range
There are two main types of default objects.
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1")
When you refer Range object, as shown above, it is referred as fully qualified reference. You have told Excel
exactly which range you want, what sheet and in what worksheet.
Example: MsgBox Worksheet("sheet1").Range("A1").Value
Using Range property, you can perform many tasks like,
As such it will be too lengthy to cover all scenarios for range property. For scenarios mentioned above, we will
demonstrate an example only for one. Refer to a Single cell using range property.
Click on button.
It will open a window.
Enter your program name here and click 'OK' button.
It will take you to main Excel file, from top menu click on 'stop' record button to stop recording Macro.
Step 4) The above step will open VBA code editor for file name "Single Cell Range". Enter the code as shown
below for selecting range "A1" from the excel.
Step 5) Now save the file and run the program as shown below.
Likewise, you can select a cell with a particular Name. For example, if you want to search cell with name
"Guru99- VBA Tutorial". You have to run the command as shown below. It will select the cell with that name.
Range("Guru99- VBA Tutorial").Select
To apply other range object here is the code sample.
Cell Property
Similarly to the range, in VBA you can also you "Cell Property". The only difference is that it has an "item"
property that you use to reference the cells on your spreadsheet. Cell property is useful in a programming loop.
For example,
VBA Macro Excel Turotial (Jibran) Page 61
Cells.item(Row, Column). Both the lines below refer to cell A1.
Cells.item(1,1) OR
Cells.item(1,"A")
Range("A1").offset(Rowoffset:=1, Columnoffset:=1).Select
The result for this will cell B2. The offset property will move A1 cell to 1 column and 1 row away. You can
change the value of rowoffset / columnoffset as per requirement. You can use a negative value (-1) to move
cells backward.
Download Excel containing above code
Summary:
The VBA Range Object represents a cell or multiple cells in your Excel worksheet
o A single cell
o A row or a column of cells
o A selection of cells
o A 3-D range
To manipulate cell values, Properties and Methods are used
o A property stores information about the object
o A method is an action of the object it will perform like select, merge, sorted, etc.
VBA follow object hierarchy pattern to refer object in Excel using .dot operator
Range property can be applied in two different types of objects
o Worksheet Objects
o Range Objects