0
  1. Initializing an array - Empty
  2. ReDim Preserve when i m in the first loop iteration
  3. When i use ReDim the code works fine - increase the size of the array, but the previous part of the array get empty.

enter image description here

  1. BUT in the second iteration i get an error in the line ReDim Preserve arrTips(Counterarr, 5) when i m trying to increase the size of the array.

enter image description here

Code:

Option Explicit

Sub test()

    Dim arrTips() As Variant
    Dim i As Long, Counterarr As Long

    'Set counter to start array
    Counterarr = 0

    For i = 1 To 10

        'Increase array lenght
        ReDim Preserve arrTips(Counterarr, 5)

        arrTips(Counterarr, 0) = ""
        arrTips(Counterarr, 1) = ""
        arrTips(Counterarr, 2) = ""
        arrTips(Counterarr, 3) = ""
        arrTips(Counterarr, 4) = ""
        arrTips(Counterarr, 5) = ""

        Counterarr = Counterarr + 1

    Next i

End Sub
3
  • You can only increase the Y on a 2D array, being Y the column. If you want to increase that, you need to transpose arrays and such... Is better to define the array from the beginning (ReDim taxes the execution time). Commented Sep 6, 2019 at 7:08
  • Have a look at this LINK Commented Sep 6, 2019 at 7:21
  • You don't say much about the project in which this array issue arises. But looking at the limited information you would be possibly better served by making the Y dimension a separate object and then storing these objects in a collection. This will make your code much more flexible and easier to modify in the future. And importantly, completely avoid the redim issue. Commented Sep 6, 2019 at 10:46

1 Answer 1

3

ReDim Preserve can only resize the last parameter but not the other ones when using Preserve.

From the offical documenation of the ReDim statement:

If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.