Could you please explain to me why this simple VBA code fails at the last line ("Subscript out of Range"):
Dim test() As Variant
ReDim test(0, 1)
test(0,0) = "key"
test(0,1) = 1
ReDim Preserve test(1, 1)
If the index is specified as a variable, check the spelling of the variable name. Dim MyArray() As Integer MyArray(8) = 234 ' Causes Error 9. Visual Basic doesn't implicitly dimension unspecified array ranges as 0 - 10. Instead, you must use Dim or ReDim to specify explicitly the number of elements in an array.
The ReDim statement is used to size or resize a dynamic array that has already been formally declared by using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). Use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
Subscript Out of Range (Run time: Error 9) Subscript Out of Range Error (Run Time: Error 9) occurs when you refer to an object or try to use a variable in a code that doesn't exist in the code, in that case, VBA will show this error. As every code that you write is unique, so the cause of the error would be.
Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array, and for every other dimension you must specify the same bound it already has in the existing array.
For example, if your array has only one dimension, you can resize that dimension and still preserve all the contents of the array, because you are changing the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension if you use Preserve.
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