VBA Primer
VBA Primer
(vba)
By learning VBA you will be able to use Excel more efficiently and effectively
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
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).
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. )
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.
Now, let us take a look at your macro and the code it contains.
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.
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).
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.
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
has a height, weight, and nationality. A property can also define the way the
object behaves. E.g., a person can think.
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.
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.
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.
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
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.
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).
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).
Selecting a cell.
o
Selecting a row.
o
Here the row number is important as you are selecting the entire row.
The column number does not play an important role.
o
Selecting a column.
o
Here the column number is important as you are selecting the entire
column. The row number does not play an important role.
o
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
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"
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
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
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
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.
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
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.
11