1

I'm trying to create a function that calculates Drawdown. It would work as follows:

  1. I have a series of quotes for a specific stock in column B: B (example)
  2. I want to know the maximum drawdown, that is, how much would be the biggest decrease in the quote. enter image description here

In this case the biggest indentation occurs in the yellow area!that is, the formula would look like: Drawdown = (MaxValue/Value)-1 ==> Drawdown = (13/9)-1

I tried as follows, with no result:

Public Function MDD(ByVal Selection0, ByVal Selection1)
    'Function Max DrawDown

    Dim i As Long
    Dim Drawdown0 As Long
    Dim Drawdown1 As Long
    
    i = 2
    
    Drawdown0 = "(" & Selection0 & "/MAX(" & Selection1 & ")) - 1"


    
    While i < Plan1.Range("B" & Rows.Count).End(xlUp).Row + 1
        Drawdown1 = "(" & Selection0 & "/MAX(" & Selection1 & ")) - 1"
        If Drawdown1 > Drawdown0 Then
            Drawdown0 = Drawdown1
        End If
        i = i + 1
    Wend
   
   MDD = Drawdown0
End Function

Sub lsMDD()
    Application.MacroOptions Macro:="MDD", Category:=4
End Sub

Where's the error?

3
  • 1
    It seems like you are conflating formulas and VBA.... Drawdown0 = "(" & Selection0 & "/MAX(" & Selection1 & ")) - 1" is trying to assign a string (text) to a Long. Commented Jun 23, 2020 at 18:00
  • @BigBen I need to use a formula to calculate or retrieve the maximum between the arranged values ​​... In this case, I am unsure how to do it. Commented Jun 23, 2020 at 18:02
  • 1
    Application.Max might be helpful. You have to actually translate the formula logic to VBA. Commented Jun 23, 2020 at 18:05

1 Answer 1

3

You don't need to iterate over the range. Look at Application.WorksheetFunction - it's got everything you need.

Public Function MDD(ByVal pRange As Variant) As Variant
    MDD = Application.WorksheetFunction.Max(pRange) / Application.WorksheetFunction.Min(pRange) - 1
End Function
Sign up to request clarification or add additional context in comments.

2 Comments

MDD takes one argument, pRange, which is the range covering your source data, say A1:A10. Application.WorksheetFunction exposes many Excel worksheet functions to VBA. Here I just used WorksheetFunction's Max and Min to do the same as formula "=MAX(A1:10)/MIN(A1:A10)-1" would have done on the worksheet.
Great! Thank you! I will study how 'Application' functions (Previously: Worked perfectly! Could you please explain to me how this function works, if you are not asking too much?) Sorry...edited

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.