I'm trying to make my Excel VBA UDF function to return an array. As of now the function either returns #VALUE! error if I define the argument as double array or all of the cells in the array have the same value if I define the argument as variant even though I checked in the Locals window in VBE and the return array variable actually contains different values.
Here is my code:
Function VaRScenariosTest(ByRef dblRealRates() As Double/Variant) As Double()
'dblRealRates() is defined as either Double or Variant
Dim intCount As Integer
Dim dblTemp() As Double
For intCount = LBound(dblRealRates) To (UBound(dblRealRates) - 1)
ReDim Preserve dblTemp(1 To intCount)
dblTemp(intCount) = dblRealRates(intCount + 1) - dblRealRates(intCount)
Next intCount
VaRScenariosTest = dblTemp
End Function
Function Range2dblArray(ByRef rngRange As Range) As Double()
Dim dblTemp() As Double
Dim intCount As Integer
For intCount = 1 To rngRange.Count
ReDim Preserve dblTemp(1 To intCount)
dblTemp(intCount) = rngRange.Cells(intCount)
Next intCount
Range2dblArray = dblTemp
End Function
I call the function in the spreadsheet in the following way: function call in excel with dblRealRates() as Double/Variant
Column E contains the input to function, column F the values that should be returned by the function and column G the function itself. If I define the dblRealRates() variable type as double, the formula returns the #VALUE! error. If I define it as variant, the returned values in the spreadsheet are the same. If I pause the execution of the code at End Function line and look in the Locals WIndow, you can actually see that the values in the array are different, not all equal to 0.000016287 as the output in the spreadsheet suggests:Function Array values in Locals Window
Can someone please advise why does the formula returns an error when the dblRealRates() variable is defined as double, and why does it return identical values if it's defined as variant?
Range2dblArray
as a UDF? Things would be easier if it didn't need to be usable from an Excel cell, and I'm not sure what use it would have as a standalone Excel function. If it didn't need to be a UDF as well, then you could just pass aRange
toVaRScenariosTest
and then that could callRange2dblArray
as the first thing it did. – YowE3KVaRScenariosTest
function is an intermediate step in a bigger calculation, therefore it will take on vba variables as arguments instead ofRange
objects. However for testing purposes I want to be able to have a look at all the intermediate steps, therefore I implemented theRange2dblArray
function to be able to passRange
objects into the intermediate functions, where I want to check the intermediate results – VBAEnthusiast