Macros & User Defined Function (VBA)
Macros & User Defined Function (VBA)
with VBA
Macros
Recording Macros
Structure of a function
Alt + F11
Within the VBA editor, select Insert | Module from the
menu
End Function
If then else
Structure
Function myTstat(p)
If p > 1.96 then myTstat = 1 else myTstat = 0
End Function
Ex:
Deposit
Interest Rate
< 10,000
5%
5.5%
6%
> 1,00,000
6.5%
Case Else
<statement>
End Select
End Function
Ex:
Function myselect(p)
Select Case p
Case Is < 10000
myselect = 0.05
Case Is < 50000
myselect = 0.055
Case Is < 100000
myselect = 0.06
Case Else
myselect = 0.065
End Select
End Function
Function BS(s, k, v, r, t)
d1 = (Application.WorksheetFunction.Ln(s / k) + (r + (v ^ 2) / 2) * t) / (v *
Sqr(t))
d2 = d1 - (v * Sqr(t))
BS = (Application.WorksheetFunction.NormSDist(d1) * s) (Application.WorksheetFunction.NormSDist(d2) * k * Exp(-r * t))
End Function
For i = 1 To p Step 1
j=j*i
Next i
myFactorial = j
End Function
Variables
Defining a variable
Range
Boolean
True / False
Integer
-32,768 to 32,767
Date
String
Text
Arrays
Compute
Backup
Loops Do While
Executes statement while the condition is true
Compute factorial
Function myFactorial2(p)
If p < 2 Then
myFactorial2 = 1
Else
i=1
j=1
Do While i <= p
j=j*i
i=i+1
Loop
myFactorial2 = j
End If
End Function
Loops Do Until
Executes statement until the condition is met
Compute factorial
Function myFactorial3(p)
If p < 2 Then
myFactorial2 = 1
Else
i=1
j=1
Do Until i > p
j=j*i
i=i+1
Loop
myFactorial2 = j
End If
End Function
Arrays
A group of variables sharing the same name & type and
referenced by an index
Declaring an array
Dim myArray(5)
Array index starts from 0
Declaring an array with index boundaries
Dim myArray(2 To 5)
Identifying the bounds of an array
LBound(myArray)
UBound(myArray)
Multi-dimension array
Dim myArray(5,5)
Dim myArray(1 To 5, 1 to 5)