I am trying to create a new UDF MaxDrawdown_General_Purpose that takes the values from selected cells or range of cells and at the same time that takes the value from an array in VBA ambient. How can i merge 2 functions below in a new one MaxDrawdown_General_Purpose ? Thank you in advance.
VBA Code:
Function MaxDrawdown(data() As Double) As Variant 'Runs only in VBA ambient
Dim N As Integer
Dim i As Integer
Dim highestPrice As Double
Dim currentPrice As Double
Dim currentDrawdown As Double
N = UBound(data)
If N > 0 Then
highestPrice = 1
MaxDrawdown = 0
For i = 0 To N - 1
currentPrice = highestPrice * (1 + data(i) / 100)
currentDrawdown = (highestPrice - currentPrice) / highestPrice
highestPrice = IIf(currentPrice > highestPrice, currentPrice, highestPrice)
MaxDrawdown = IIf(currentDrawdown > MaxDrawdown, currentDrawdown, MaxDrawdown)
Next i
MaxDrawdown = 100 * MaxDrawdown
Else
MaxDrawdown = "undefined"
End If
End Function
Function MaxDrawdownExcel2(rng As Range) As Double 'Runs only in Excel
Dim N As Integer
Dim i As Integer
Dim highestPrice As Double
Dim currentPrice As Double
Dim currentDrawdown As Double
Dim data() As Variant
data = rng.Value
N = UBound(data)
If N > 0 Then
highestPrice = 1
MaxDrawdownExcel2 = 0
For i = 1 To N
currentPrice = highestPrice * (1 + data(i, 1) / 100)
currentDrawdown = (highestPrice - currentPrice) / highestPrice
highestPrice = IIf(currentPrice > highestPrice, currentPrice, highestPrice)
MaxDrawdownExcel2 = IIf(currentDrawdown > MaxDrawdownExcel2, currentDrawdown, MaxDrawdownExcel2)
Next i
MaxDrawdownExcel2 = 100 * MaxDrawdownExcel2
Else
MaxDrawdownExcel2 = "undefined"
End If
End Function
Last edited by a moderator: