Search code examples
vbafunctionindexingexcel-formulaweibull

Cannot use result of index in vba function for further computation


I'm building a custom function in Excel VBA to receive the nth (here: 5th) element of an array with a Webull distribution. This works, but then I cannot do further computations with the result such as simple multiplication without getting an error.

enter image description here

Function weib(xr, shape, scaler)
    n = Application.Weibull_Dist(xr, shape, scaler * 100, 0)
    weib = n
End Function

Function good(xr, shape, scaler)
    n = Application.Index(Application.Weibull_Dist(xr, shape, scaler * 100, 0), 5, 0)
    good = n
End Function

Function nogood(xr, shape, scaler)
    n = Application.Index(Application.Weibull_Dist(xr, shape, scaler * 100, 0), 5, 0) * 1
    nogood = n
End Function

Why does the "nogood" function not work? It only adds * 1 at the end - how can I fix it?


Solution

  • In testing, n is a Variant array with a lower bound of 1. That'll cause a Type Mismatch when attempting to multiply by 1. So one (inferior) solution is:

    Function good(xr, shape, scaler)
        n = Application.Index(Application.Weibull_Dist(xr, shape, scaler * 100, 0), 5, 0)
        good = n(1)
    End Function
    
    Function nogood(xr, shape, scaler)
        n = Application.Index(Application.Weibull_Dist(xr, shape, scaler * 100, 0), 5, 0)
        nogood = n(1) * 1
    End Function
    

    The better solution is to use 1 instead of 0 in the Index call:

    Function good(xr, shape, scaler)
        n = Application.Index(Application.Weibull_Dist(xr, shape, scaler * 100, 0), 5, 1)
        good = n
    End Function
    
    Function nogood(xr, shape, scaler)
        n = Application.Index(Application.Weibull_Dist(xr, shape, scaler * 100, 0), 5, 1) * 1
        nogood = n
    End Function
    

    You can even skip using Index entirely (maybe the best solution):

    Function good(xr, shape, scaler)
        good = Application.Weibull_Dist(xr, shape, scaler * 100, 0)(5, 1)
    End Function
    
    Function nogood(xr, shape, scaler)
        nogood = Application.Weibull_Dist(xr, shape, scaler * 100, 0)(5, 1) * 1
    End Function