70
78
Advanced Modelling in Finance
Function BSOptValue(iopt, S, X, r, q, tyr, sigma)
’ returns the Black-Scholes value (iopt=1 for call, -1 for put, q = div yld)
’ uses fns BSDOne and BSDTwo
Dim ert, eqt, NDOne, NDTwo
ert = exp(-r
Ł
tyr)
eqt = exp(-q
Ł
tyr)
NDOne= Application.NormSDist(iopt
Ł
BSDOne(S, X, r, tyr, sigma))
NDTwo= Application.NormSDist(ioptŁ BSDTwo(S, X, r, tyr, sigma))
BSOptValue = iopt
Ł
(S
Ł
eqt
Ł
NDOne - X
Ł
ert
Ł
NDTwo)
EndFunction
Function BSDOne(S, X, r, q, tyr, sigma)
’ returns the Black - Scholes d1 value
BSDOne = (log(S/X) + (r-q +0.5ŁsigmaO2)Łtyr)/(sigmaŁsqr(tyr))
EndFunction
Function BSDTwo(S, X, r, q, tyr, sigma)
’ returns the Black-Scholes d2 value
BSDTwo = (log(S/X)+(r-q - 0.5
Ł
sigmaO2)
Ł
tyr)/(sigma
Ł
sqr(tyr))
EndFunction
Note that the intermediate quantities, DOne and DTwo, have been coded as functions
in their own right and are simply called from the ‘master’ function. The object is to
modularise the VBA code making its operation more transparent and allowing errors in
coding to be pinned down more accurately.
In summary, functions are VBA procedures which return values, their code being
enclosed in between the keywords Function and End Function. Following the Function
keyword, the name of the function is declared followed by a list of inputs in brackets.
Aseries of VBA statements follow and when the function has run, the name returns
the output:
Function name (input1, input2, ...)
[statements]
[name = expression]
End Function
In good VBA programming, it is preferable to head each Module sheet with the Option
Explicit statement, which forces formal variable declaration. Note that whereas all vari-
ables created and used in computing the function should be declared with Dim statements,
variables that are function inputs do not need to be declared. If Excel functions are
required in the code, they must be referred to with theApplication. or theWorksheet-
Function.prefix.
4.4 MANIPULATING ARRAYS IN VBA
Unfortunately, there is a step change in the complexity of coding functions with array
input and output. Therefore before developing such functions, it is worth considering how
arrays are handled in Excel. In many instances, familiar Excel functions such as SUM,
AVERAGE, STDEV, SUMPRODUCT and NPV can be employed to take care of the
array handling. In other cases, additional safeguards are required to code array handling
so that it performs as intended. In particular:
ž In the absence of suitable built-in functions, it may be necessary to process individual
array elements, so repeated operations in a loop are required. If so, the number of