A Brief Introduction To VBA
A Brief Introduction To VBA
1
Overview
The purpose of this presentation is to provide you with
a very brief introduction to VBA, a programming
language that is embedded within the Microsoft Office
suite of software products.
2
Overview
In particular this presentation will :
Show you how to record a macro and then edit it.
subroutines.
Discuss how to insert modules for functions and
3
Macros and VBA
VBA is Visual Basic for Applications. It is a modified
version of Microsoft’s well-known Visual Basic language.
Although many users treat VBA as nothing more than a
macro-language, in truth it can be much more. It allows:
moderately complex programming,
one to include in VBA programs some of the functions that are
built into Excel,
it allows the user to read data from and write data into Excel,
and it allows the user to create programs that can use various
components from the Microsoft suite of products.
The key to realize is that VBA is a tool to use to
supplement Excel.
4
Macros and VBA
Most users of Excel are at least somewhat familiar to macros. We
will start with a simple Macro example, and then examine the
structure and code of the example to begin to gain insight into
VBA.
To begin, open a new workbook in Excel
Click on the Tools menu, and look toward the bottom. One of
choice.
You will then receive a pop-up window, asking you to name your
6
Macros and VBA
After typing in the line of text (and, of course, pressing
the “enter” key), press the F5 button again, this time tell
Excel to go to cell c15.
Once you get to cell c15, enter “=today()”. This is a
function that simply puts today’s date in the cell.
Now, let’s stop the macro recording. To do this click on
the little blue square in the macro popup box that is on
the screen.
To demonstrate that the macro works, clear the entire
spreadsheet. To do this, press ctrl-A to highlight the
entire spreadsheet and then press the delete key.
7
Macros and VBA
Now we can demonstrate that the macro works. Again
click on the “tools” menu and select “macro”.
This time, however, select the first option “Macros”.
This will bring up a list of all macros in the spreadsheet
(there will likely only be one, the one you just created
labeled “create_text”). Select “create_text”, and then
click on the RUN button. This will run your macro.
8
Macros and VBA
We can now examine the macro. The macro is really just
a small subroutine written in VBA. To see the macro
text, just once again click on Tools, Macro, and then
click once on your macro name. Then click on the “Edit”
button.
This will bring up a new item on your application bar –
the Microsoft Visual Basic Editor (we’ll show another way
of bringing this up later.)
Your program should look something like this:
9
Macros and VBA
Sub create_text()
'
' create_text Macro
' Macro recorded 7/28/2003
'
'
Application.Goto Reference:="R1C1"
ActiveCell.FormulaR1C1 = “FINN 6210 Title Page"
Range("A2").Select
Application.Goto Reference:="R10C3"
ActiveCell.FormulaR1C1 = "=TODAY()"
Range("C11").Select
End Sub
10
Macros and VBA
Notice that the “macro” is enclosed between two lines:
sub create_text()
end sub
11
Macros and VBA
Each line of the program is executed sequentially – that
is, one after the other. Let’s look at what each line does
The first several lines (all beginning with ') are simply
comment lines that VBA ignores.
'
' create_text Macro
' Macro recorded 7/28/2003
'
12
Macros and VBA
Application.Goto Reference:="R1C1“
This line is how the macro tells the spreadsheet to go to cell A1.
“Application.Goto” means for VBA to use the “GOTO” function
from the application – in this case from Excel (remember VBA
can be used from Word, Access, and other Office applications.)
So literally “Application.Goto” means, use the function named
“goto” embedded in this application.
The second part of this line , Reference:=“R1C1” tells VBA to go
to row 1, column 1 (which is column “A”).
Note that later on, when we want to go to cell C10, we use the
same line, but with Reference:”R10C3”.
13
Macros and VBA
The “Application.” construct is important in VBA. For the
most part, you can access any of Excel’s built in functions
that way!
14
Macros and VBA
The “Application.Goto” command is used again, this time
to go to cell c10.
Application.Goto Reference:="R10C3"
Notice that the only difference between that line and the
line where we entered our text, is that instead of
entering just the text, it puts the equal signs inside of
the quote.
15
Macros and VBA
Notice that you can easily modify your macro now that
you are in the program. For example, you could modify
the text to say “My modified title page”. Just go to the
line that says
ActiveCell.FormulaR1C1 = "Financial Modeling Title Page“
16
Macros and VBA
Using the Macro record feature has a lot of advantages,
especially if you would like to learn the appropriate VBA
code or command, but it is of only limited use when
trying to develop more complex program – such as a
program than can take conditional actions, or that
repeat an action for a specific (or even conditional)
number of times.
To do that, we really need to be able to create programs
without first recording them as macros.
We will examine how to do this in the next several
sections.
17
Creating a Program
So how do you create a program in VBA? Its relatively
easy.
To make our example clear, shut down Excel, and then
restart it, opening a clean spreadsheet.
Once again, click on the “Tools” menu and select
“Macro”.
This time however, select the option on the menu
labeled “Visual Basic Editor”. This will open up a new
window (and new item on your application bar at the
bottom of you screen.)
18
Creating a Program
This new screen – the VBA editor – is very busy and has a
lot of very useful tools on it, but for now we are largely
going to ignore them and focus on building some very
simple tools.
To do this we first need to find a place to enter our new
program: we must create a “module” in which to store it.
Do to this click on the “insert” menu and then click on
“module”.
This will open up a white-screen on the right side of the
screen.
We are now almost ready to begin, but first we have to
decide what type of program to create.
19
Subroutines vs. Functions
As mentioned a moment ago, Macros are considered
subroutines within VBA. In actuality, however, there are
two types of programs in VBA that we will examine,
subroutines and functions.
Subroutines are the more general of the two – they
perform any number of activities.
Functions are more specific types of programs. They
accept a fixed number of inputs and then return a single
value back to the user. The nice thing about a function
is that you can call it from within excel in exactly the
same way that you call an Excel function – by putting
the = sign in front of the name!
20
Functions
Because they are somewhat more limited (and also
because you are more likely to use them first), we will
begin with functions.
Let us begin with a very simple function, one that takes
two numbers, let’s call them a and b, adds them
together and then returns them to the user. Let’s call
this function adder. Thus, once written, we will call it
from Excel entering the line:
=adder(a,b)
Where a and b would be replaced by actual numbers.
21
Functions
To begin with we have to tell Excel we are creating a
function and tell it the name of that function. To do this
we enter the following:
function adder(a, b)
This says that you are creating the function adder and
that the user will supply to parameters, a and b.
Notice that as soon as you type this in, Excel
automatically adds the line
end function
22
Functions
All of the lines for this function must go between those
two lines.
We are going to make the simplest possible function: on
the first line simply type:
adder = a+b
23
Functions
Go back to your main spreadsheet (click on the Excel tab
on the bottom of your screen).
Select any cell you like, type in
=adder(5,5)
=adder(12,12)
Notice that 24 is now entered in the new cell, but 10 is
24
Functions
Indeed, you can notice that you can use the adder
function within excel just like you would use any Excel
function.
For example, the Excel Function max(y,z) places in the
cell the greater of the two values y or z. Type in the
following line:
=max(10,adder(13,-2))
The adder function evaluates to 11, and that is the max
of 10 and 11, and so it is returned.
25
Functions
You can even have recursive calling of a function
(meaning the function can call itself):
=adder(5,adder(3,6))
Will equal 14.
function pres_val(cf,r,n)
Again, excel will put the “end function” line in for you.
This says that your function will need three inputs, the
27
Functions
We may want to calculate an intermediate result and to
temporarily store it. We will need a variable to store
those numbers. To create a variable in a VBA program,
use the dim command. Let’s create a variable, pv_factor
Function pres_val(cf,r,n)
Dim pv_factor
End function
28
Functions
We can now use this variable in an intermediate role
(albeit a rather silly one in this example
Function pres_val(cf,r,n)
Dim pv_factor
pv_factor = (1+r)^-n
pres_val = cf*pv_factor
End function
29
Functions
What the program does now is clear:
1. It creates the variable pv_factor to hold the present
value factor determined by r and n.
2. It then determines the actual present value by
multiplying pv_factor by the cash flow.
3. It then returns the present value back to the calling
function or routine.
30
Functions vs. Subroutines
For our purposes, there are very few differences
between programming a function and a subroutine.
There is one very important difference, however:
A function cannot directly write data back to the spreadsheet, it
can only return the one value that it calcualtes.
A subroutine can write data back to the spreadsheet whenever it
wants.
31
Functions vs. Subroutines
To read data directly from a spreadsheet into a variable,
use the following command:
variable = cells(row,column).value
where variable is the name of the variable, row is the
row number of the cell containing the value, and column
is the column number (not letter, you must use a
number!)
Example: Let’s say that you wanted to read the contents of cell
b4 and to store it in the variable r. The line to do this would
read:
r = cells(4,2).value
32
Functions vs. Subroutines
Writing data back to the spreadsheet is just as easy.
Let’s say that you have calculated a variable x that you
want to write back to cell d8. You would use the
following command to do this:
cells(8,4).value = x
33
Other Items
We have not yet gotten into a couple of other key
issues, how to control the flow of your program, and
how to make loops.
35
Other Items
Here is the code for the function MaxFinder
' A very simple use of an if-then loop.
Function MaxFinder(a, b)
Dim temp
If a > b Then
temp = a
Else
temp = b
End If
MaxFinder = temp
End Function
36
Another Example
Finally, there is another example spreadsheet on my
web-paged named “Starting Point.xls.” This spreadsheet
contains an extremely well-documented subroutine that
will read cash flows and an interest rate from the
spreadsheet, will calculate the present value of those
cash flows, and will return that present value to the
spreadsheet.
This subroutine uses all of the tools that we have
developed in this set of slides.
37