0

I am trying to do a ReDim of a multidimensional array and get a Subscript out of Range error.

I currently have this code:

Public Sub redim_test()

    Dim data() As Double
    
    ReDim data(0, 3)
    
    Debug.Print "before " & UBound(data) & "," & UBound(data, 2)
    ReDim Preserve data(UBound(data, 1) + 1, 3) 'subscript out of range occurs here
    Debug.Print "before " & UBound(data) & "," & UBound(data, 2)

End Sub

The intention is that as the sub starts, it sets the first and second dimensions of the array to 0 and 3 respectively.

It then prints the bounds before attempting to ReDim the first dimension, so that we end up with data(1,3), before printing out the bounds to confirm they have changed.

I cannot see why this shouldn't work but also cannot see the error...

I realise on the face of this, ReDim'ing the array twice in the same Sub actually achieves nothing as it could be done in one go, but this is an abbreviated function with much of the original content removed in order to try and find the cause of the Subscript our of Range error and this is the minimum which I can reduce to in order to demonstrate the problem.

cosmarchy
  • 686
  • 3
  • 9
  • 21
  • 2
    one cannot redim preserve and change anything but the last dimension. you are trying to change the first, that is not possible. – Scott Craner Mar 23 '22 at 19:39
  • Here is a function that allows the change of size of a 3D array: https://stackoverflow.com/questions/66054936/redim-preserving-3d-vba Just remove the Z loop and criteria. – Scott Craner Mar 23 '22 at 19:42

0 Answers0