Excel-VBA 2007 appears to have a 64k limit on the size of arrays passed as arguments.
Is anyone aware of a fix or work-around?
Here's the code:
Public Function funA(n)
Dim ar()
ReDim ar(n)
funA = ar
End Function
Public Function funB(x)
funB = UBound(x)
End Function
From Excel:
=funB(funA(2^16-1)) '65536 as expected
=funB(funA(2^16)) 'Gives a #VALUE
Looking inside, funA() works fine but, passed to funB, the argument x is an Error 2015.
As @paxdiablo mentioned the size of array is about 400+ Mb, with theoretical maximum of 2 Gb for 32 bit Excel. Most probably VBA macroses are limited in memory usage.
Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO. Array Index cannot be negative. VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable.
Arrays can be passed to proceedures by putting () after the name of the array variable. Arrays must be passed by reference. If no passing mechanism is specified, e.g. myFunction(arr()) , then VBA will assume ByRef by default, however it is good coding practice to make it explicit.
The limit is less than the number of rows by the number of columns in the worksheet which is 1048576 rows by 16384 columns (Excel specifications and limits).
I think it's a limitation of the spreadsheet cell itself, rather than VBA. Excel can pass arrays bigger than 2^16 between functions, but apparently it can't contain an array of that size within a cell.
As an experiment, highlight funA(2^16)
in the cell formula and hit F9 - it'll give you a '#VALUE!'
error.
Because the formula has already calculated the result of funA
before it initiates funB
, it's then trying to run funB
on a function that's already calculated to an error.
It seems a work-around like the one Brad posted (i.e. a third function that calculates funB(funA(n))
within itself) keeps the cell out of the equation until the calculation's completed, so it works fine.
Because single-dimensional arrays are passed back to Excel as a row of columns you have hit the Excel 2007 limit on the number of columns (64K).
If you make your array 2 dimensional and return as rows it should work:
Public Function funA(n)
Dim ar()
ReDim ar(n,1)
funA = ar
End Function
Alternatively you can use Transpose to rotate the array from a row to a column, but this is probably less efficient than creating a 2-dimensional array in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With