Macro Basics
Macro Basics
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
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.
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
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.
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.
Your complete code window should now look 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,
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.
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.
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
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.
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.
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 arrays
HERE,
Code Action
Dynamic arrays
The syntax for declaring DYNAMIC arrays is as follows:
HERE,
Code Action
ReDim arrayName(4) 2. It specifies the array size after the array has been defined.
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
Dim Drinks(1 To 4) As It declares an array variable called Drinks. The first array
String index is 1 and the last array index is 4.
Drinks(1) = "Pepsi" Assigns the value Pepsi to the first array element. The
other similar code does the same for the other elements
in the array.
Sheet1.Cells(2, 1).Value = Writes the value of the array element with index 1 to row
Drinks(1) number two of column 1
Summary
3 CheckBox Used for true or false values. Multiple check boxes can have true value at the same
time.
7 Spin Button Used to increment or decrease numeric values by clicking on up or down arrows
that appear in the spin button
8 Option Used for true or false values. Only one option button can have a true value at a time.
Button
If you hover the mouse over control, the name of the control will appear as shown
below
Adding GUI controls to a spreadsheet
We will now add a command button to our workbook, for that we have to
Step 1) In this step, click the option "insert button" from the Active X Control. Then
select the command button option from it.
Step 4) Check you are on the right sheet. A code editor will open. Enter your code.
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
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).
6 mod Modulus Operator: Divides a number and returns the reminder 10 mod 3 1
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.
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".
1 & Concatenate: This operator is used to concatenate strings "John " & John
together "Doe" Doe
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.
1 = Equal: checks if two values are equal. It If x = z Returns true if they are equal,
is also used as an assignment operator Then else it returns false
2 < Less than: This operator is used to If x < z Returns true if x is less than z,
subtract numbers Then else it returns false
3 > Greater than: This operator is used to If x > z Returns true if x is greater
multiply numbers Then than z, else it returns false
4 <> Not equal to: This operator is used to If x <> z Returns true if they are not
divide numbers Then equal, else it returns false
5 <= Less than or equal to: If x <= z Returns true if x is less than or
Then equal to z, else it returns false
6 >= Greater than or equal to: If x >= Returns true if x is greater
Then than z, 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.
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.
1 AND AND: This is used to combine more than one condition. If true = true false
If all the conditions are true, AND evaluates to true. If AND false = true
any of the condition is false, AND evaluates to false THEN
2 OR OR: This is used to combine more than one condition. If If true = true OR true
any of the conditions evaluate to true, OR returns true. If true = false
all of them are false, OR returns false THEN
3 NOT NOT: This one works like an inverse function. If the If NOT (true) false
condition is true, it returns false, and if a condition is Then
false, it returns true.
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,
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.
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
Code Action
"ByVal arg1 As String, ByVal It declares two parameters of string data type name arg1
arg2 As String" : 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
MsgBox firstName & " " & It calls the MsgBox built-in function to display a
lastName" message box. It then passes the 'firstName' and
'lastName' variables as parameters.
The ampersand "&" is used to concatenate the two
variables and add an empty space between them.
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:
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
myFunction = arg1 + arg2 evaluates the expression arg1 + arg2 and assigns the
result to the name of the function.
"End Function" "End Sub" is used to end the body of the function
Functions are very similar to the subroutine. The major difference between a
subroutine and a function is that the function returns a value when it is called. While
a subroutine does not return a value, when it is called. Let's say you want to add two
numbers. You can create a function that accepts two numbers and returns the sum
of the numbers.
Code Action
Code Action
Step 4) Run the program, you will get the following results
Download Excel containing above code
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.
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
Worksheet Objects
Range 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.
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