Guru99 VBA
Guru99 VBA
Guru99 VBA
Tutorial
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.
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.
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
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.
Go to the local drive where you have stored the CSV file
Select the CSV file
Click on Import button
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.
Summary
Macros simplify our work lives by automating most of the routine works that we do.
Macros in Excel are powered by Visual Basic for Applications.
How to Create Visual Basic for
Applications (VBA) in Excel with Examples
Everybody in this country should learn how to program a computer... because it teaches
you how to think." -Steve Jobs
I wish to extend the wise words of Steve Jobs and say everyone in the world should learn
how to program a computer. You may not necessary end up working as a programming or
writing programs at all but it will teach you how to think.
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
For business use, you can create complete powerful programs powered by excel and VBA.
The advantage of this approach is you can leverage the powerful features of excel in your
own custom programs.
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.
HERE,
"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.
=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
The following image shows the complete source code
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 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.
Download the above Excel Code
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.
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.)
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.
Here are some example for Valid and Invalid names for variables in VBA.
In VBA, we need to declare the variables before using them by assigning names and data
type.
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 3): Open the Macro editor, enter the code for variable in the Macro1
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 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.
You can either specify the scope as private by default or public. For example,
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.
VBA Array: Dynamic, Multidimensional
with Example in Excel
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.
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.
Static arrays
HERE,
Code Action
1. It declares an array variable called arrayName with a size of n
Dim arrayName and datatype. Size refers to the number of elements that the
(n) datatype array can store.
Dynamic arrays
HERE,
Code Action
1. It declares an array variable called arrayName without
Dim arrayName ()
specifying the number of elements
datatype
2. It specifies the array size after the array has been defined.
ReDim arrayName(4)
Array Dimensions
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).
Note: This section assumes you are familiar with the process of creating an interface in
excel. If you are not familiar, read the tutorial VBA Subroutines and Functions. It will show
you how to create the interface
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
Dim Drinks(1 To 4) As
index is 1 and the last array index is 4.
String
Assigns the value Pepsi to the first array element. The
other similar code does the same for the other elements in
Drinks(1) = "Pepsi"
the array.
Summary
Used for true or false values. Multiple check boxes can have true value at the same
3 CheckBox
time.
Option Used for true or false values. Only one option button can have a true value at a
8
Button time.
If you hover the mouse over control, the name of the control will appear as shown below
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
Step 1) In this step, click the option "insert button" from the Active X Control. Then select
the command button option from it.
Step 2) To insert "clickcommandbutton1" drag the mouse cursor to Excel sheet.
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".
Download the above Excel Code
Prerequisite
Configure Microsoft Excel
As we see in previous tutorial, make sure your ribbon will have "Developer" icon as shown
here.
Now, rename sheet1 to "VBA Operator" as shown in screen-shot below. Save the workbook
in an Excel Macro-Enabled Workbook (*.xlsm) file extension. (see the image below).
After that, click on Save button.
6 mod Modulus Operator: Divides a number and returns the reminder 10 mod 3 1
Add a button to the Excel sheet as we show earlier, and then follow the following points
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.
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".
Comparison operators are used to compare values for validation purposes. Let's say you
are developing a simple point of sale application. In this application, you want to validate
the values entered before you post. In such cases, you can use comparison operators. This
operator will check against the negative numbers or to ensure that the amount paid does
not exceed the billed amount. Comparison operators come in handy in such situations.
Equal: checks if two values are equal. It is If x = z Returns true if they are equal,
1 =
also used as an assignment operator Then else it returns false
Less than: This operator is used to If x < z Returns true if x is less than z,
2 <
subtract numbers Then else it returns false
Greater than: This operator is used to If x > z Returns true if x is greater than
3 >
multiply numbers Then z, else it returns false
Not equal to: This operator is used to If x <> z Returns true if they are not
4 <>
divide numbers Then equal, else it returns false
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"
"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.
The following table shows the properties that you need to change and the values that you
need to update too.
Caption OR Operator (1 = 1) Or (5 = 0)
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,
"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.
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.
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
VBA Syntax for declaring subroutines
Private Sub mySubRoutine(ByVal arg1 As String, ByVal arg2 As String)
'do something
End Sub
Code Action
Here the keyword "Sub" is used to declare a subroutine
named "mySubRoutine" and start the body of the
"Private Sub
subroutine.
mySubRoutine(…)"
The keyword Private is used to specify the scope of the
subroutine
"ByVal arg1 As String, ByVal It declares two parameters of string data type name
arg2 As String" : arg1 and arg2
"End Sub" "End Sub" is used to end the body of the subroutine
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.
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
Code Actions
"Private Sub It declares a private subroutine displayFullName that
displayFullName(…)" accepts two string parameters.
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
Add the following code in code editor for the click event of btnDisplayFullName command
button.
On the developer toolbar put the design mode 'off'. As shown below.
Step 5) Click on the command button 'FullName Subroutine'.
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
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.
The advantages of using functions are the same as the ones in the above section on why use
subroutines.
The rules for naming functions as the same as the ones in the above section on rules for
naming subroutines.
Code Action
Here the keyword "Function" is used to declare a
function named "myFunction" and start the body of
"Private Function
the function.
myFunction(…)"
The keyword 'Private' is used to specify the scope of
the function
"ByVal arg1 As Integer, ByVal It declares two parameters of integer data type named
arg2 As Integer" 'arg1' and 'arg2.'
"End Function" "End Sub" is used to end the body of the function
Code Action
Code Action
Step 4) Run the program, you will get the following results
Download Excel containing above code
Summary:
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
What is VBA Range?
The VBA Range Object represents a cell or multiple cells in your Excel worksheet. It is the
most important object of Excel VBA. By using Excel VBA range object, you can refer to,
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.
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
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.
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.
Here, we will use ".Select" command to select the single cell from the sheet.
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 3) In next step,
Click on Macro button from the top menu. It will open the window below.
In this window, Click on the 'edit' button.
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.
For example,
Cells.item(1,1) OR
Cells.item(1,"A")
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.
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