When you declare Dim Arr(0) As Long
, you're creating a static (fixed-size) array. Then you pass it to DoSomethingWithArray
as a Variant
using ByRef
. Inside that procedure, you overwrite ArrayArg
with a new array (localArr
), which causes VBA to attempt to reassign the reference.
But here's the catch:
Fixed-size arrays passed as ByRef to Variant parameters behave unpredictably when reassigned inside the procedure.
The reassignment ArrayArg = localArr
doesn't just overwrite the contents—it breaks the reference and causes the original array (Arr
) to be zeroed out.
This is because VBA tries to reconcile the static array reference with the new dynamic array assignment, and in doing so, it essentially resets the original array.
If you want predictable behavior, use a dynamic array instead:
Sub TestFixedSizeArrayAsByRefVariantArgument()
Dim Arr As Variant
ReDim Arr(0) As Long
Arr(0) = 99
DoSomethingWithArray Arr
Debug.Print Arr(0) ' Outputs -1 as expected
End Sub
This works because Arr
is a Variant
holding a dynamic array, so reassignment inside the procedure behaves as expected.