0% found this document useful (0 votes)
97 views

VBA Primer

Excel VBA

Uploaded by

Kabir Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

VBA Primer

Excel VBA

Uploaded by

Kabir Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

What is Visual Basic for Applications

(vba)

VBA is a programming language used to give instructions to Excel (and also


Word, PowerPoint and other software)

Why learn VBA?

By learning VBA you will be able to use Excel more efficiently and effectively

You will also learn to think logically

What is needed from you

You do not need to be a programmer or have prior programming experience

You should be ready to put in a lot of time experimenting and practicing

You should have the Developer menu or tab on Excel. (If you do not see a
Developer menu, go to Excel Options, Popular, and check Show Developer
tab in the ribbon

Where in excel is the vba program or


code?

Code is stored in a module

You can look at modules in the Visual Basic Editor

You can go to the Visual Basic Editor by pressing ALT-F11

What is the Visual Basic Editor (VBE)?

Just as a workbook holds worksheets, the VBE is a place which holds


o

Modules (that contain the actual code or program. Modules are like
files that contain one or more programs)

Project Explorer (like the Windows Explorer, the Project Explorer shows
what workbooks are open, what worksheets there are in each
workbook, and what modules are there. You may also see files that
you do not recognize. These are files used by Excel, you do not need
to worry about them.)

The Properties Window which shows the properties of the module that
we are looking at. (To start with, do not bother with the Properties
Window, and you can close it as you would any other window, by
clicking on the X on the top right of the window).

Kannan Ramanathan 2012

Updated on May 6th 2012

How to record a macro?

Just as Excel is a computer program, a macro is a small program. Macros are


sometimes also referred to as procedures. Macros can be created by the user
for use in Excel (and in many other programs)

A simple way to start understanding macros (or procedures or programs) is to


record a macro

Just as a voice recording captures your voice, recording a macro in Excel


captures your actions in Excel

To record a macro, you must have the Developer tab on your menu. Click on
the Developer tab. To the left, you will see a button for Record Macro. Click
on this button. You will be asked for four things. Some of these are optional,
but go ahead and get into the habit of providing all four items of information
asked
o

First, provide a Macro Name. Call it FirstMacro. (Note that the macro
name should be one word, without spaces, and should not start with a
number).

Second, provide a Shortcut Key. (The shortcut key is the Control key,
followed by a letter. Just as clicking on the play button on your voice
recorder will play your voice, clicking the Shortcut Key will repeat your
actions in Excel. )

Third, provide a location to store the module. (Should the module be


stored in your current workbook, a new workbook, or a workbook called
Personal Macro Workbook? Usually you will store the macro in the
current workbook.)

Finally, provide a description of what the macro is going to do.

Once you have provided this information, and click Ok, your macro will
begin recording. Note that the Record Macro on the Developer Tab has
changed to Stop Recording. Your actions in Excel are now being recorded.

Click on cell A1 on your worksheet. Type Hello World and press enter.
When you press enter, the cursor moves to the cell below, cell A2. Now click
on Stop Recording. Congratulations, you have just recorded your first
macro. When you save the workbook, the macro is also stored along with the
workbook.

Kannan Ramanathan 2012

Updated on May 6th 2012

Looking at the code in the macro

Now, let us take a look at your macro and the code it contains.

On the Developer Tab, click on the Macros button. Next to Macros in is a


window with a drop down box. Choose This Workbook from the drop down
box. You will see the name of the macro you recorded in the large window
titled Macro Name. Click on FirstMacro. Then click on edit. You will see
something very similar to the following
Sub FirstMacro()
' Macro1 Macro
' Description that you provided for this macro
' Keyboard Shortcut: Ctrl+l
ActiveCell.FormulaR1C1 = "Hello World"
Range("A2").Select
End Sub

What do the lines in the code mean?

VBA conveniently gives the words in the code different colors which makes it
easy for us to read the code. Words in blue are reserved words, or keywords
that mean specific things to Excel. For example, you cannot use the word
Sub as a macro name. Words in green are comments.

Comments are provided for the benefit of the user, and are not lines in the
program itself. For example, the description of the program you provided is
shown as a comment. Comments start with a single quotation mark. You can
write anything here. Excel does not care what you write and will ignore any
line that starts with a single quotation mark.

The first line in each macro begins with the word Sub followed by the name
of the macro and the first line ends with open and close parentheses like this
(). The last line has the words End Sub. The entire program or macro has to
be contained within the lines Sub, and End Sub. If you have any text before
the Sub line or after the End Sub line, or Excel will indicate an error when
you try to run the macro.

The line ActiveCell.FormulaR1C1 = "Hello World indicates that you entered


the words Hello World in the active cell. The active cell is simply the cell
where the cursor is in Excel. FormulaR1C1 is Excels way of referring to the
value in that cell. The period . separates the cell from a property of the cell
which is its value. Just as you can say Car.Door to refer to the door of your
car, or Car.Engine to refer to the engine of your car, you can say
Activecell.FormulaR1C1 to indicate the value in the cell where your cursor is.
The cell is considered an object (just as your car is an object). The
characteristic (of value) is considered to be a property or attribute of the
object (just as the car door is an attribute of the car).

Kannan Ramanathan 2012

Updated on May 6th 2012

Without getting into technical details, let us briefly understand three


important components of Visual Basic: objects, properties and methods.

Replaying the macro

Go to any cell in any worksheet of the workbook. Press the short cut key that
you provided when you recorded the macro. The macro will enter Hello
World in the active cell, that is the cell in which you are now. After it enters
Hello World the macro will then activate cell A2 (because that is where you
went after you entered Hello World).

Other ways of replaying the macro

Go to the module in which the procedure is found. When your cursor is on


any line of code then press function key F5. This will cause the program to
run. You could also go step through the code one line at a time. To do this
you will press function key F8. Each time you press F8 one line of the code
will be executed. As you do this, you could keep your cursor over different
variable names. A small box will popup telling you what the value of the
variable is. By stepping through the code one line at a time you can confirm
(by placing your cursor over a variable name) that that variable is taking on
the values you programmed.

When you have many lines of code, you may want to run your macro upto a
certain point and then step through the remaining lines of code. To do this,
you want to create a break in the code by positioning your cursor on a line
of code and pressing F9. Excel VBA will highlight the line with the break in a
different color. By pressing F9 while on that same line of code, you can
remove the break.

What are objects in Excel?

An object represents a building block in Excel such as a cell, a worksheet or a


workbook. The Excel Object Model refers to a description of all the objects in
Excel.

A collection is a group of objects. A collection is itself an object. You can


think of UTD as an object which is a collection of schools. Schools are
collections of buildings. Buildings are collections of classrooms (and other
rooms). Similarly, you can think of the Excel application as an object that is a
collection of different workbooks that you may have open at the same time.
Each workbook is a collection of worksheets. Each worksheet is a collection
of cells.

What are Properties in Excel?

Properties are something which an object has. Properties describe the object.
E.g., the Range object has the property Title. That means that a range can
have a title. Properties define the characteristics of an object. E.g., a person

Kannan Ramanathan 2012

Updated on May 6th 2012

has a height, weight, and nationality. A property can also define the way the
object behaves. E.g., a person can think.

What are Methods in Excel?

Methods do something to or with the object. A method is an action that can be


performed on or with objects. For example, a cat is an object. You can say
Car.Door.Open to indicate open car door. Similarly you can say
Range.Delete to say that the range should be deleted.

What are Events in Excel VBA?

Events are various things that can happen in a program such as Visual Basic.
Visual Basic programs are structured around events. For instance, activating
a worksheet is an event. We can write a program that is triggered when the
user activates a worksheet.

What is the Object Browser?

When you are in the Visual Basic Editor (VBE), press F2 (function key F2) to
see the Object Browser. The Object Browser shows the objects and the
methods and properties (if any) associated with it. The green symbol next to
an item indicates that the item a method. The hand symbol indicates that
the item is a property.

How to invoke built-in Excel functions?

Some, but not all, of the functions that you can use in a worksheet are
available for use in VBA. E.g., you can use functions such as LEFT, RIGHT, or
MID, in Excel VBA and Excel VBA will understand you are referring to string
functions. However, some other functions such as Vlookup, are not directly
usable in VBA. To use (or invoke) these functions, you need to prefix these
functions with the words APPLICATION.WORKSHEETFUNCTION. This tells VBA
that you are invoking (or using, or calling) a function that is normally used in
a worksheet. Unfortunately, not all worksheet functions are available for use
in VBA (even by using the APPLICATION.WORKSHEETFUNCTION prefix).
Luckily for us, we do not have to remember which functions are available and
which are not. When you are in the Visual Basic Editor (VBE) and type
APPLICATION.WORKSHEETFUNCTION. (that is application period
worksheetfunction period) Excel VBA helpfully provides a list of available
worksheet functions.

What does Option Explicit do?

It is good practice (but not absolutely necessary) to use the Option Explicit
statement. This statement must appear before any procedures in a module.
When Option Explicit appears in a module, you must explicitly declare all
variables. Declaring a variable means introducing the variable. For

Kannan Ramanathan 2012

Updated on May 6th 2012

example, you can delcare the variable GradePoints by writing:


Dim GradePoints as Integer

This statement says that you will be using the variable GradePoints to hold
integer values. (You cannot assign decimal values, or string values to this
variable). If you do not know what kind of values it will hold, you can still
declare the variable as follows:
Dim GradePoints as Variant

The as variant simply means that the variable GradePoints can hold any
value, whether it is a string, decimal value, integer or other value type. The
advantage of using Option Explicit statement is, among other things, it helps
us prevent making spelling errors in declaring variables.

What is an activecell, activeworksheet,


activeworkbook?

Activecell is the cell in which the cursor is presently in. (In VBA code, the
activecell refers to the cell which will be read, or where a value will be
placed).

Activeworksheet is the worksheet presently being processed, or referred to.

Activeworkbook is the current workbook (when you have more than one
workbook open, activeworkbook helps select the workbook where you want
actions to be completed).

How to select a cell, row, column,


range?

Selecting a cell.
o

You can select a cell with the code:


Cells(RowNumber, ColumnNumber).select

RowNumber and ColumnNumber supply the two arguments for the


Cells() function. You do not have to call the two arguments
RowNumber and ColumnNumber. You can call the two arguments
almost anything you want. (There are some rules for naming variables
but you will not usually have a problem with this). Note that the first
argument for the Cells() function is always the row number and the
second argument is always the column number.

Selecting a row.
o

You can select a row with the code:


Cells(SpecificRowNumber, AnyColumnNumber).entirerow.select

Here the row number is important as you are selecting the entire row.
The column number does not play an important role.
o

You can also select a row with the code:


Range("A1").EntireRow.Select

Kannan Ramanathan 2012

Updated on May 6th 2012

Here, row 1 will be selected

Selecting a column.
o

You can select a column with the code:


Cells(AnyRowNumber, SpecificColumnNumber).entirecolumn.select

Here the column number is important as you are selecting the entire
column. The row number does not play an important role.
o

You can also select a column with the code:


Range("A1").EntireColumn.Select

Here, column A will be selected

Selecting a range.
o

You can select a range in different ways. Remember that for a range,
one end of the range is the upper left cell and the other end is the
lower right cell in a rectangular block. Both the upper left cell of the
range and the lower right cell of the range, are determined by their
respective row and column numbers.
Using the cells approach, you can select a range in one of the following
ways:
Range(Cells(2, 3), Cells(10, 4)).Select
Range("C2:D10").Select

Examples of Code

The following examples of code need to be copied and pasted in a module.


When you are in the Visual Basic Editor, you can create a module by clicking
on the Insert menu and then choosing Module. If you have recorded a macro
and stored it in that workbook, you will see that it already has a module. A
module can have more than one macro (also known as procedure) in it.

If-Then Condition

You are familiar with the IF condition in an Excel worksheet. Here is how to
use the IF condition in Visual Basic for Applications. In any worksheet type
the number 100 into cell A1. Then copy and paste the following code in a
module.
Sub Grading()
GradePoints = ActiveSheet.Range("A1").Value
If GradePoints > 93 Then
LetterGrade = "A"
ElseIf GradePoints > 83 Then
LetterGrade = "B"
ElseIf GradePoints > 73 Then
LetterGrade = "C"
Else
LetterGrade = "F"

Kannan Ramanathan 2012

Updated on May 6th 2012

End If
ActiveSheet.Range("B1").Value = LetterGrade
End Sub

If you change the number 100 in cell A1 to 50, the letter grade in cell B1 will
change from A to F.
The first line (after the name of the macro) takes the value in cell A1 in the
active sheet and stores it in a variable called GradePoints. The IF condition
starts with the word IF, and ends with END IF. As you can see it is very logical
and easy to follow. It is not necessary to have ELSEIF as part of your IF
condition. ELSEIF is useful if you have multiple possible values in the IF
condition.

For-Next Loop

Visual Basic for Applications is very useful if you want to do a repetitive task.
Let us say that you want to put a number starting from 1 to 100 in 100 cells,
and that you want to color even numbers red and odd numbers green. Here is
the code to do this.
Sub OddEvenColor()
For rownumber = 1 To 100
Cells(rownumber, 1).Value = rownumber
If Application.WorksheetFunction.IsEven(rownumber) Then
Cells(rownumber, 1).Interior.Color = vbRed
Else
Cells(rownumber, 1).Interior.Color = vbGreen
End If
Next
End Sub

The first line (after the name of the macro) starts a counter from 1 to 100.
Just as we started the IF condition with IF and finished it with END IF, a FOR
loop starts with FOR and ends with NEXT. Here the loop assigns the value 1
to a variable. The variable is rownumber.
(You can call the variable anything you like, except for keywords. If you do
use a keyword as a variable name, Excel will alert you. As long as you use
characters from the English alphabet, start the variable name with a letter,
and do not use punctuation marks you will not experience problems.)
Each time the program sees NEXT it increments the variable rownumber by
one till it completes 100.
The line Cells(rownumber, 1).Value = rownumber assigns the value represented
by rownumber to a cell. The reserved word cells has two arguments: the
first number represents the row, and the second number represents the
column. You can refer to any cell on the active sheet by referring to that
cells row and column. (If you do not specify which worksheet, it is assumed
that the cells are in the current worksheet in the current workbook.)
The next line If Application.WorksheetFunction.IsEven(rownumber) Then checks if
the rownumber is even. To do this, we use the function IsEven(). The

Kannan Ramanathan 2012

Updated on May 6th 2012

function IsEven() takes one argument, a number. If the number is even, the
function returns the value TRUE. We read this as saying it is true that
rownumber is even. The function IsEven() is available for use in a worksheet.
To let Excel know that we are using a function that is available in a worksheet
we write the code as: Application.WorksheetFunction.IsEven(rownumber).
If the cell contains an even number then we want to color the cell red. We
take the cell object and refer to its interior property. (This distinguishes it
from the cells border property. So we can use different commands to color
the border differently). We then assign the color red to the interior of the cell.
Colors in VBA can be represented by various numbers which are difficult to
remember. For convenience, Excel provides some values that are called
constants. vbRed, vbGreen, vbYellow etc., are constants.

For-Each-Next Loop

This loop is useful to address all objects in a collection. For instance, you
want to name each worksheet in your workbook JohnDoeSheet1,
JohnDoeSheet2 and so forth. You can do this as follows:
Sub NameSheetJohnDoe ()
For Each wsSheet In ActiveWorkbook.Worksheets
wsCount = wsCount + 1
wsSheet.Name = "JohnDoeSheet" & wscount
Next wsSheet
End Sub

The first line (after the name of the procedure, or macro) refers to each object
in the collection. Here the collection is all the worksheets in the
activeworkbook. (Activeworkbook is the workbook you are currently in. You
could have other workbooks open, but these will not be affected). wsSheet is
the variable name to represent each object in the collection.
The line wsCount = wsCount + 1 is used to increment the variable wscount by
one each time it is encountered.
The line wsSheet.Name refers to the Name property of the object wsSheet.
The line Next wsSheet closes the loop and the code repeats from the line For
Each till each object in the collection has been addressed.

If you wanted to name all worksheets in all open workbooks, you can set up a
loop inside another loop.
Sub NameSheetJohnDoe()
For Each wrkbook In Application.Workbooks
wrkbook.Activate
For Each wsSheet In ActiveWorkbook.Worksheets
wscount = wscount + 1
wsSheet.Name = "JohnDoeSheet" & wscount
Next wsSheet
Next wrkbook
End Sub

Kannan Ramanathan 2012

Updated on May 6th 2012

The first line (after the procedure name) refers to the collection of workbook
objects in the Excel application. One by one, the code activates each
workbook object in the collection so that that workbook becomes the
ActiveWorkbook. It then names each sheet in the active workbook.

Do-While Loop
Suppose you want to do an action while some condition is true, and you want
to continue doing this action till that action becomes false. For such an
action, you will use a Do While loop.
In the following example we want to toss three coins and see if all three coins
turn up heads. We will keep tossing three coins at a time, till such time we
get three heads. We want to determine the number of tosses it takes before
we get three heads together. We will use the following code.
Sub ThreeHeadsTogether()
ThreeHeads = False
Do While ThreeHeads = False
CoinTossNumber = CoinTossNumber + 1
'we will assume that if Coin1 has a value of 1 it is heads, otherwise
tails
Coin1 = Application.WorksheetFunction.RandBetween(1, 2)
Coin2 = Application.WorksheetFunction.RandBetween(1, 2)
Coin3 = Application.WorksheetFunction.RandBetween(1, 2)
If Coin1 = 1 And Coin2 = 1 And Coin3 = 1 Then
ThreeHeads = True
End If
Loop
MsgBox CoinTossNumber
End Sub

To start, we declare a variable ThreeHeads to have a value of False. Then,


the next line Do While ThreeHeads = False starts the loop that will be repeated
as long as the variable ThreeHeads as a value False.
To keep track of how many times we are tossing the coins, we have a variable
CoinTossNumber that is incremented each time we toss the coins.
We then toss three coins, Coin1, Coin2 and Coin3. We will generate a random
number between 1 and 2. That is each time we generate the random
number, we get either 1 or 2. We will also assume that a 1 represents heads
and 2 represents tails. To generate a random number we will use the
worksheet function RandBetween(1,2). The RandBetween(x,y) function takes
two arguments: the first provides the lower boundary, the second provides
the upper boundary. Since the RandBetween function is a worksheet function
we have to indicate this by writing
Application.WorksheetFunction.RandBetween(1,2).
The random value generated is stored in the three variables Coin1, Coin2,
and Coin3.
The IF THEN condition evaluates if all three coins are showing heads. If they
are, then the variable ThreeHeads takes the value TRUE.

Kannan Ramanathan 2012

Updated on May 6th 2012

10

The Loop then goes back to the Do While ThreeHeads=False line. But
ThreeHeads now has the value True, so the loop does not continue.
The line MsgBox CoinTossNumber shows the values of the CoinTossNumber
which reflects how many times we tossed the three coins.

Select Case End Select

The Select Case code begins with Select Case and ends with End Select. It
works similar to the IF-THEN-END IF construct. The procedure that we wrote
earlier called Grading is repeated below but this time using Select Case.
Sub Grading()
GradePoints = ActiveSheet.Range("A1").Value
Select Case GradePoints
Case Is > 93
LetterGrade = "A"
Case Is > 83
LetterGrade = "B"
Case Is > 73
LetterGrade = "C"
Case Else
LetterGrade = "F"
End Select
ActiveSheet.Range("B1").Value = LetterGrade
End Sub

Where to store code?

You usually store code in a module. The module can reside in the current
workbook or the Personal Macro Workbook. Whenever you start Excel, the
Personal Macro Workbook opens automatically. Any macro that is stored in
the Personal Macro Workbook is then available for you.

For instance, if you have a macro that expands a column or increases the
height of a row, and store this macro in the Personal Macro Workbook, then
you can invoke (or use, or call) the macro from any worksheet that you are
working in.

FYI, Excel stores the Personal Macro Workbook in a folder called XLSTART.
Any file that is stored in XLSTART is opened automatically each time that you
open Excel. You may find it convenient to keep the Personal Macro Workbook
hidden so that you have the macros in that workbook available for use, but it
does not get in the way of your work.

Other references for Excel VBA


http://www.jlathamsite.com/Teach/VBA/ProgrammingInExcelVBA_AnIntroduction.pdf

Kannan Ramanathan 2012

Updated on May 6th 2012

11

You might also like