Search code examples
excelvba

VBA ByRef argument type mismatch in Excel 2019


Another failed attempt to escape from VBA. I am trying to parse a string in Excel VBA into two variables. I do bring up the non-common sense portion in my head to work on it but still no luck.

Sub StartEndMonth(ByVal MonthRange As String, ByRef MonthStart As String, ByRef MonthEnd As String) ' xxx-xxx
    MonthStart = "Jan"
    MonthEnd = "Dec"
End Sub

Sub TestMonthList()
    Dim Month_Range, Start_Month, End_Month As String
    Month_Range = "Jan-Dec"
    StartEndMonth Month_Range, Start_Month, End_Month
    MsgBox MonthRange & " " & Start_Month & " " & End_Month
End Sub

The above code throws the VBA ByRef argument type mismatch error on the Start_Month variable in the calling routine. I should have some parsing logic inside the StartEndMonth routine. I still got the compile error after I have eliminated everything else in the routine.

Suppose every variable has been properly defined? Or not?

Thanks for the help!


Solution

  • As a general rule, don't write subs/functions that modify their arguments. If you calculate something, return it, e.g. as an Array:

    Function SplitMonthRange(MonthRange As String)
        SplitMonthRange = Split(MonthRange, "-")
        ' you really should add some sanity checks, e.g. UBound() and value checks
    End Function
    

    Then the res works very straight-forward:

    Sub TestSplitMonthRange()
        Dim monthRange as String, months As Variant
    
        monthRange = "Jan-Dec"
        months = SplitMonthRange(monthRange)
    
        MsgBox monthRange & ": " & months(0) & " to " & months(1)
    End Sub
    

    Hint - this:

    Dim Month_Range, Start_Month, End_Month As String
    

    declares 2 Variants and 1 String. This is correct:

    Dim Month_Range As String, Start_Month As String, End_Month As String