Guru99 Macro
Guru99 Macro
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.
The importance of macros in Excel
Let's say you work as a cashier for a water utility company. Some of the customers pay through the bank and at the
end of the day, you are required to download the data from the bank and format it in a format that meets your business
requirements.
You can import the data into Excel and format. The following day you will be required to perform the same ritual. It
will soon become boring and tedious. Macros solve such problems by automating such routine tasks. You can use
a macro to record the steps of
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
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.
We will create a macro enabled template that will import the above data and format it to meet our business reporting
requirements.
Step 3) Now another window will open, in that window do following things
First, we will see how we can create a command button on the spreadsheet and execute the program.
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
Before we save our work book, we will need to delete the imported data. We will do this to create a template that we
will be copying every time we have new receipts and want to run the ImportBankReceipts macro.
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?
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
You will now be able to see the DEVELOPER tab in the ribbon
"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.
Your complete code window should now look as follows
Close the code window
Right click on button 1 and select edit text
Enter Say hello
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
Create the GUI using excel cells as shown below
Add a command button between rows 7 and 8
Give the button macro name btnCalculateEMI_Click
Click on edit button
Enter the following code
Dim monthly_rate As Single, loan_amount As Double, number_of_periods As Single, emi As Double
monthly_rate = Range("B6").Value / Range("B5").Value
loan_amount = Range("B3").Value
number_of_periods = Range("B4").Value * Range("B5").Value
emi = WorksheetFunction.Pmt(monthly_rate, number_of_periods, -loan_amount)
Range("B9").Value = emi
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
The following image shows the complete source code
Click on save and close the code window
Test your program as shown in the animated image below
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.
It will open a VBA editor on the right-hand side of the folder. It will appear like a white space.
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
Step 6) When you click on Run button, the program will get executed. It will display the msg in MsgBox.
VBA Variables
VBA Data-Types
Constant in VBA
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.
Step 2) In next step, right-click on the button and select View code. It will open the code window as shown below.
Step 3) In this step,
Name
Joining Date
Income in curreny
Constant in VBA
Constant is like a variable, but you cannot modify it. To declare a constant in VBA you use keyword Const.
There are two types of constant,
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.
VBA Array: Dynamic, Multidimensional with
What is an Array?
An array is a memory location capable of storing more than one value. The values must all be of the same data type.
Let's say you want to store a list of your favourite beverages in a single variable, you can use an array to do that.
By using an array, you can refer to the related values by the same name. You can use an index or subscript to tell them
apart. The individual values are referred as the elements of the array. They are contiguous from index 0 through the
highest index value.
This tutorial assumes you are using Microsoft Excel version 2013. The knowledge still applies to other versions of
Microsoft Excel as well.
In this tutorial, you will learn-
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.
For Example: Dim ArrayMonth(12) As String
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.
For Example: Dim ArrayMonth(12) As Variant
Syntax for declaring arrays
Static arrays
The syntax for declaring STATIC arrays is as follows:
Dim arrayName (n) as datatype
HERE,
Code Action
Dim arrayName (n) 1. It declares an array variable called arrayName with a size of n and datatype. Size refers
datatype to the number of elements that the array can store.
Dynamic arrays
The syntax for declaring DYNAMIC arrays is as follows:
Dim arrayName() as datatype
ReDim arrayName(4)
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
Let do this exercise step by step,
Step 1 – Create a new workbook
Drinks(1) = "Pepsi"
Drinks(2) = "Coke"
Drinks(3) = "Fanta"
Drinks(4) = "Juice"
If you hover the mouse over control, the name of the control will appear as shown below
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.
Close the window when you are done.
You will get the following results.
How to use ActiveX control in VBA
In this section, we will see how to incorporate 'commandclick' button in VBA and execute a program using the button.
Step 1) In this step, click the option "insert button" from the Active X Control. Then select the command button
option from it.
Step 3) Then right click on the command button and select option "View Code".
Step 4) Check you are on the right sheet. A code editor will open. Enter your 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 6) In Excel sheet, you will see Design Mode tab is on. Make sure it is "OFF" or else your code will not work.
Step 7) When design mode is off, there will be no green highlight on it. Now you can Click on the command button.
Step 8) Click on "CommandButton1". It will print "Guru99 VBA Tutorial" in the cell range "A1 to A10".
Prerequisite
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
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.
S/N Operator Description Example Output
1 & Concatenate: This operator is used to concatenate strings together "John " & "Doe" John Doe
VBA Comparison Operators: Not equal to, Less than or equal to, Greater than
"If 2 = 1 Then… Else… End If" uses the if statement to evaluate the condition "2 = 1"
"MsgBox…" Is a built-in function that displays a message box.
o The first parameter "True" or "False" is what will be displayed in the message box. In our example, 2
is not equal to 1, therefore, it will show "false" in the msg box.
o The second parameter "vbOKOnly" is the button that is displayed in the message box
o The third parameter "Equal Operator" is the title of the message box.
Executing the above code gives the following results
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.
S/N Operator Description Example Output
AND: This is used to combine more than one condition. If all the
If true = true AND
1 AND conditions are true, AND evaluates to true. If any of the condition is false
false = true THEN
false, AND evaluates to false
OR: This is used to combine more than one condition. If any of the
If true = true OR
2 OR conditions evaluate to true, OR returns true. If all of them are false, OR true
true = false THEN
returns false
NOT: This one works like an inverse function. If the condition is true, it
3 NOT If NOT (true) Then false
returns false, and if a condition is false, it returns true.
"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.
Add the following code to btnOR_Click
Private Sub btnOR_Click()
If (1 = 1) Or (5 = 0) Then
MsgBox "OR evaluated to TRUE", vbOKOnly, "OR operator"
Else
MsgBox "OR evaluated to FALSE", vbOKOnly, "OR operator"
End If
End Sub
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.
Add the following code to btnNOT_Click
Private Sub btnNOT_Click()
If Not (0 = 0) Then
MsgBox "NOT evaluated to TRUE", vbOKOnly, "NOT operator"
Else
MsgBox "NOT evaluated to FALSE", vbOKOnly, "NOT operator"
End If
End Sub
HERE,
"If Not (0 = 0) Then" the if statement uses the NOT logical operator to negate the result of the condition. If
the conditions is true, the code below 'Else' keyword is executed. If the condition is true, the code above Else
keyword is executed.
Excel VBA: Call a Subroutine
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-
Break code into small manageable code: An average computer program has thousands and thousands of
source code lines. This introduces complexity. Subroutines help solve this problem by breaking down the
program into small manageable chunks of code.
Code reusability. Let's say you have a program that needs to access the database, almost all of the windows
in the program will need to interact with the database. Instead of writing separate code for these windows, you
can create a function that handles all database interactions. You can then call it from whichever window you
want.
Subroutines and functions are self-documenting. Let's say you have a function calculateLoanInterest and
another that says connectToDatabase. By just looking at the name of the subroutine/function, the programmer
will be able to tell what the program does.
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 1) User Interface
Design the user interface as shown in the image below
Right click on the command button as shown in the image below. Select View Code.
The code editor will open
Add the following code in code editor for the click event of btnDisplayFullName command button.
Private Sub btnDisplayFullName_Click()
displayFullName "John", "Doe"
End Sub
Your code window should now look as follows
Save the changes and close the code window.
Step 4) Testing the code
On the developer toolbar put the design mode 'off'. As shown below.
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.
Excel VBA Function Tutorial: Return, Call, Examples
Details
Last Updated: 13 August 2018
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.
A function is a piece of code that performs a specific task. A function returns a value after execution.
Both subroutines and functions offer code reusability
Both subroutines and functions help break down large chunks of code into small manageable code.
Excel VBA Range Object
Details
Last Updated: 28 June 2018
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.
To manipulate these cell values, Properties and Methods are used.
Worksheet Objects
Range Objects
Syntax for 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.
Step 6) You will see Cell "A1" is selected after execution of the program.
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.
Range for selecting cell in Excel Range declared
For single Row Range("1:1")
For single Column Range("A: A")
For Contiguous Cells Range("A1:C5")
For Non-Contiguous Cells Range("A1:C5, F1:F5")
Range("A1:C5 F1:F5")
For Intersection of two ranges
(For intersection cell, remember there is no comma operator)
Range("A1:C5")
To merge Cell
( To merge cell use "merge" command)
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,
Cells.item(Row, Column). Both the lines below refer to cell A1.
Cells.item(1,1) OR
Cells.item(1,"A")
Range Offset property
Range offset property will select rows/columns away from its original position. On the basis of the range declared,
cells are selected. See example below.
For example,
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