0% found this document useful (0 votes)
8 views19 pages

FIN452&537 Appendix A IntroToVBA SP25

This document provides an introduction to Visual Basic for Applications (VBA) as used in Excel, covering essential topics such as syntax, variable declarations, subroutines, functions, and debugging techniques. It outlines how to create and manage VBA modules, perform mathematical operations, and utilize loops and conditional statements. The document serves as a guide for students in finance courses to effectively use VBA for advanced derivative securities modeling.

Uploaded by

Jiajun Nie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views19 pages

FIN452&537 Appendix A IntroToVBA SP25

This document provides an introduction to Visual Basic for Applications (VBA) as used in Excel, covering essential topics such as syntax, variable declarations, subroutines, functions, and debugging techniques. It outlines how to create and manage VBA modules, perform mathematical operations, and utilize loops and conditional statements. The document serves as a guide for students in finance courses to effectively use VBA for advanced derivative securities modeling.

Uploaded by

Jiajun Nie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Advanced Derivative Securities

Appendix A
Introduction to VBA

Professor Jian Cai


Outline

1. An Overview of VBA
2. VBA Editor and Modules
3. VBA Basic Syntax
4. Variables and Assignments
5. Conditional Statements
6. Variable Declarations
7. Arrays
8. Debugging

2 FIN 452 & 537 / Jian Cai / Spring 2025


VBA in Excel
 VBA means “Visual Basic for Applications.”
 Programs can easily be translated into any other language.
 Excel is a good environment for many exercises.
 A few special features of Excel are being used, in particular
the cumulative normal distribution function and the random
number generator (also included in MATLAB).
 You are expected to already have it on your computer. If not,
add the “Developer” tab under Options/Customize Ribbon on
a PC or under Preferences/Ribbon (in the Sharing and Privacy
section) on a Mac.
 A good reference: Jackson and Staunton (2001), “Advanced
Modelling in Finance Using Excel and VBA,” Wiley, New York.

3 FIN 452 & 537 / Jian Cai / Spring 2025


VBA Editor and Modules

 Subroutines and functions are created in the VBA editor, which


is reached through Developer/Visual Basic.

 A module is a collection of subroutines and/or functions.

 To add a module, click Insert/Module to open an editing screen


in which subroutines and functions can be typed.

 If you save the Excel workbook, all of its modules (and hence
subroutines and functions in them) are saved with the
workbook.

 All of the subroutines and all of the functions in all of the


modules in any open workbook are available to use in all open
workbooks.

4 FIN 452 & 537 / Jian Cai / Spring 2025


Subroutines and Functions

 Each subroutine starts with Sub and ends with End Sub, and
each function starts with Function and ends with End
Function.

 A subroutine is also called a macro. To execute a macro, click


Tools/Macros in VBA Editor then double click the macro name,
or click Developer/Macros directly in Excel.

 A user-defined function is executed just like any other Excel


function, that is, in a cell of the Excel spreadsheet, type
=FunctionName(arguments). The arguments supplied to
the functions can be numbers or can be cell references.

5 FIN 452 & 537 / Jian Cai / Spring 2025


Basic Syntax
 VBA ignores everything after an apostrophe. So comments
can be placed on any line by preceding them with an
apostrophe.

 The underscore character indicates that a line is to be


continued.
y = x + 5
is the same as
y = x _
+ 5

 Message Box and Input Box


Sub AnotherSub()
x = InputBox("What is your favorite number?")
MsgBox("Your favorite number was " & x)
End Sub

6 FIN 452 & 537 / Jian Cai / Spring 2025


Writing to and Reading from Cells
 You can write a number, text, or formula to any cell in any
worksheet of any open workbook. For example, executing the
following macro
Sub WritingTest()
Dim x
Workbooks("Book1").Sheets("Sheet1") _
.Range("B3").Value = 7
Range("B3").Activate
ActiveCell.Value="some text"
ActiveCell.Offset(1,2)="=A6"
x=ActiveCell.Offset(1,2)
End Sub
will write the number 7 to cell B3 of Sheet1 of Book1.xlsm, write
some text to the active cell (i.e., the cell in which the cursor is),
and write =A6 to the cell that is 1 row below and 2 columns to the
right of the active cell, whose value is assigned to x.

7 FIN 452 & 537 / Jian Cai / Spring 2025


Variables and Assignments
 Variable names must begin with a letter and cannot include
various special characters (in particular, they cannot contain
blank spaces, hyphens, or periods). Variable names are not
case sensitive: a is the same variable as A.

 You cannot use any name already reserved by VBA or Excel,


for example, Sub.

 An expression like y = x + 3 is an assignment statement.


A statement like x = x + 3 is valid.

 If you type “Option Explicit” in a VBA module, then all variables


must be declared. If you do not type “Option Explicit,” then any
undefined variable is given the value 0. The main virtue of
selecting “Option Explicit” is that it helps to avoid typos.

8 FIN 452 & 537 / Jian Cai / Spring 2025


Mathematical Operations
 The basic mathematical operations are performed in VBA in
the same way as in Excel: + (3+2), - (3-2), * (4*5), division
(5/2), exponentiation (3^2), natural exponential (Exp(6) for
e6), square root (Sqr rather than Sqrt as in Excel), natural
logarithm (Log rather than Ln as in Excel).
 It does not matter whether or not you capitalize the names of
the mathematical functions; the VBA editor will automatically
capitalize, converting for example exp to Exp.
 Other mathematical functions are used in VBA by preceding
their Excel names with Application. For example,
Application.Max(3,4) returns the larger of 3 and 4.
 In the workbook for the course, a draw from the standard
normal distribution can be generated by calling a user-defined
function RandN() (explained in Chapter 2).

9 FIN 452 & 537 / Jian Cai / Spring 2025


Loops for Repeated Executions
 A “for loop” runs commands for a fixed number of times.
Sub AddIntegers()
x = 1 • The default is to increase i by one each time.
For i = 2 To 10 • You can also define the step size; negative
x = x + i and non-integer step sizes are acceptable.
Next i • For example, For i = 2 To 10 Step 2.
ActiveCell.Value = x
End Sub

 A “while loop” runs commands until a condition is violated.


Sub AddIntegers2()
x = 0
i = 1
Do While (i <= 10 And x <= 20) Or x*i < 50
x = x + i
i = i + 1
Loop
ActiveCell.Value = x
End Sub

10 FIN 452 & 537 / Jian Cai / Spring 2025


Conditional Statements
 If statement. For example,
If y <= 10 Then
x = 2 * x
End If
 If...Else... statement. For example,
If y <= 10 Then
x = 2 * x
Else
x = 3 * x
End If
 If...ElseIf... statement. For example,
If y <= 10 Then
x = 2 * x
ElseIf y <= 20 Then
x = 3 * x
Else
x = 5 * x
End If

11 FIN 452 & 537 / Jian Cai / Spring 2025


Variable Declarations (I)

 Always use “Option Explicit” and declare all variables except


for the arguments of functions. Variables are declared with the
keyword “Dim” at the beginning of a program.
Function AddTwo(x)
As in the textbook (and in this
Dim y
course), data type here is left
y = x + 2 unspecified (hence as Variant)
AddTwo = y except that the type of an array
End Function variable must be declared.
Function TestFunction(x) The Variant data type requires
TestFunction = x * AddTwo(x) more memory for storage, so it
End Function is a bit inefficient.

 The result of TestFunction(3) is 3 × 5 = 15.

12 FIN 452 & 537 / Jian Cai / Spring 2025


Variable Declarations (II)
 Variables declared within a function or subroutine are “local
variables.” They can only be accessed within the function or
subroutine within which they are defined. Consider
Function TestFunction2(x)
Dim z
z = x * AddTwo(x)
TestFunction2 = y
End Function

 If TestFunction2(3) is executed, then if “Option Explicit”


has been declared, an error message will appear with the
information that the variable y has not been declared within
TestFunction2.
 The error message is probably preferable in this circumstance,
which points again to the benefit of having the “Option Explicit”
declaration.

13 FIN 452 & 537 / Jian Cai / Spring 2025


Variable Passing

 Do not change the value of arguments inside a


subroutine or function. Consider
Function AddTwo(x)
x = x + 2
AddTwo = x
End Function

 If TestFunction(3) is executed, then we get 5 × 5 =


25, which is unintended.

14 FIN 452 & 537 / Jian Cai / Spring 2025


Arrays (I)
 It is very useful to be able to use a single variable name to
store multiple values. For example:
For i = 1 To 10
x(i) = whatever
Next i

 An array variable must be declared (e.g., Dim x(10)),


regardless of whether “Option Explicit” is declared. Some
other examples: Dim x(4,20), Dim x(2,5,15).

 The default in VBA is that the first element is indexed by 0.


Therefore, Dim x(10) creates a row vector with 11 elements,
which are accessed as x(0), . . . , x(10). But the first
index does not have to be zero. For example, the declaration
Dim x(1 To 10) creates a vector with 10 elements, starting
the indexing at 1 and ending at 10.

15 FIN 452 & 537 / Jian Cai / Spring 2025


Arrays (II)

 The Array function is one example of a function that also


creates an array. For example,
Dim x
x = Array(3, 6, 7)
will create an array with elements x(0)=3, x(1)=6, and x(2)=7.

 Functions can take arrays as inputs and return arrays as


outputs. For example, {3, 1, 2; 4, 6, 2} is an array with two
rows and three columns, the first row being {3, 1, 2} and the
second row being {4, 6, 2}. The same array might be input via
cell references as B3:D4.

16 FIN 452 & 537 / Jian Cai / Spring 2025


Arrays (III)
 Arrays can also be output to Excel worksheets. Consider:
Function MyArray(x)
Dim y(3)
For i = 1 To 3
y(i) = i * x
Next i
MyArray = y
End Function

 If we execute the function by typing =MyArray(2) in a cell,


the number 0 will appear. The elements will be y(0)=0,
y(1)=2, y(2)=4, and y(3)=6.

 To see the rest of the output, highlight the active cell and the
three cells immediately to the right on the same row. Click the
function key F2 and then hold down the key combination
CTRL-SHIFT-ENTER.

17 FIN 452 & 537 / Jian Cai / Spring 2025


Arrays (IV)
 Arrays can also be output to Excel worksheets in the column
form using the Transpose function. Consider the following:
Function MyArray2(x)
Dim y(3)
For i = 1 To 3
y(i) = i * x
Next i
MyArray2 = Application.WorksheetFunction._
Transpose(y)
End Function

 MyArray2(2) creates an array with the same elements as


MyArray(2), but as a column vector. To see the entire
output, highlight the active cell and the three cells immediately
below in the same column. Click the function key F2 and then
hold down the key combination CTRL-SHIFT-ENTER.

18 FIN 452 & 537 / Jian Cai / Spring 2025


Debugging
 Errors (bugs) are inevitable. VBA will catch some typos but not
all. Debug each program carefully.

 To debug a subroutine, put the cursor on the subroutine name


in the Visual Basic editor. Click on Debug/Step Into (or the
function key F8) to step through the subroutine one line at a
time.

 Putting the cursor over any variable will show the value of the
variable at that stage of the program.

 Click on Run/Reset to discontinue debugging.

 To debug a function, one can rewrite it as a subroutine,


defining values for the input variables at the beginning of the
subroutine.

19 FIN 452 & 537 / Jian Cai / Spring 2025

You might also like