Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscript out of Range with ReDim (VBA)

Tags:

arrays

vba

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)
like image 397
reggie Avatar asked Oct 21 '11 09:10

reggie


People also ask

How do I fix subscript out of range error in VBA?

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.

What does ReDim mean in VBA?

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.

Why does this code generate a subscript out of range error?

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.


1 Answers

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.

like image 141
Emir Akaydın Avatar answered Oct 31 '22 14:10

Emir Akaydın