PDA

View Full Version : Solved: Function with multiple exit points



Bazman
04-07-2009, 01:35 AM
See the code below:

When I get to LR =M1 or LR=M2 I want to stop the program right there, how can I so this?

I know Goto's are a strict no no.

Function LR(AmerorEuro As String, CallorPut As String, S As Double, K As Double, v As Double, _
T As Double, r As Double, q As Double, N As Integer, output As String) As Double

Dim Val() As Double
Dim d1 As Double, d2 As Double
Dim p1 As Double, p2 As Double
Dim u As Double, d As Double
Dim i As Integer, j As Integer, Typ As Integer
Dim dt As Double, disc As Double
Dim delta As Double, gamma As Double, theta As Double


If N Mod 2 = 0 Then
N = N + 1
End If

ReDim Val(0 To N)

dt = T / N
disc = Exp(-r * dt)

If CallorPut = "c" Then
Typ = 1
ElseIf CallorPut = "p" Then
Typ = -1
End If

d1 = BSd1(S, K, v, T, r, q)
d2 = BSd2(S, K, v, T, r, q)

p1 = PPNI(d1, N)
p2 = PPNI(d2, N)

u = Exp((r - q) * dt) * p1 / p2
d = (Exp((r - q) * dt) - p2 * u) / (1 - p2)

For i = 1 To N
Val(i) = Application.Max(0, Typ * (S * u ^ i * d ^ (N - i) - K))
Next i

If output = "M1" Or output = "M2" Then
Dim Prob() As Double
ReDim Prob(N)
Dim Stock() As Double
ReDim Stock(N)
Dim M1 As Double, M2 As Double

For i = 0 To N

Prob(i) = Application.Combin(N, i) * p2 ^ i * (1 - p2) ^ (N - i)
Stock(i) = S * u ^ i * d ^ (N - i)
M1 = M1 + Prob(i) * Stock(i)
M2 = M2 + Prob(i) * Stock(i) * Stock(i)
Next i

If output = "M1" Then
LR = M1
ElseIf output = "M2" Then
LR = M2
End If

End If



For j = N - 1 To 0 Step -1
For i = 0 To j

If AmerorEuro = "e" Then
Val(i) = disc * (p2 * Val(i + 1) + (1 - p2) * Val(i))
ElseIf AmerorEuro = "a" Then
Val(i) = Application.Max((Typ * (S * u ^ i * d ^ (j - i) - K)), disc * (p2 * Val(i + 1) _
+ (1 - p2) * Val(i)))
End If

Next i

If j = 1 Then
delta = (Val(1) - Val(0)) / (S * u - S * d)
End If

If j = 2 Then
gamma = ((Val(2) - Val(1)) / (S * u ^ 2 - S * u * d) - (Val(1) - Val(0)) / (S * u * d - S * d ^ 2)) _
/ (S * u - S * d)
theta = Val(1)
End If

Next j

If output = "p" Then
LR = Val(0)
ElseIf output = "d" Then
LR = delta
ElseIf output = "g" Then
LR = gamma
ElseIf output = "v" Then
Dim change As Double, valinc As Double
change = 0.01
valinc = LR(AmerorEuro, CallorPut, S, K, v + change, T, r, q, N, "p")
LR = (valinc - Val(0)) / change
ElseIf output = "t" Then
LR = ((theta - Val(0)) / (2 * dt)) / 365
ElseIf output = "r" Then
change = 0.01
valinc = LR(AmerorEuro, CallorPut, S, K, v, T, r + change, q, N, "p")
LR = (valinc - Val(0)) / change
End If
End Function

Bob Phillips
04-07-2009, 01:47 AM
Issue an Exit Function statement

Bob Phillips
04-07-2009, 01:48 AM
BTW, use code tags (the VBA icon in the message dialog box), it makes it far easier to read.

Bazman
04-07-2009, 01:55 AM
thanks will do!