Search code examples
arraysexcelexcel-2013vba

redefining a 2 dimensional array


I'm kind of struggling of redefining an array. I have simplified my code, see below:

Sub Knop1_Klikken()
'all the cells are defined in an array
Dim col, i As Integer, defrow As Long
Dim notAct(1 To 20, 1 To 43) As Integer

For col = 2 To 4
    For row = 1 To 20
        notAct(row, kol) = 0 'setting 0 not required after Dim
        Cells(row, kol).Value = notAct(row, kol)
    Next row
Next col
'a loop with a if-statement to see if a specifica
For x = 1 To 100
    If notAct(2, 2) = 0 Then
             i = i + 1
             If i = 10 Then
                notAct(2, 2) = 1
             End If
    End If
Next x

End Sub

The thing is that I wanted to redim the array. I tried to do this just after the for-loop next x

MsgBox notAct(2, 2) 'it returns a 0
ReDim notAct(2, 2)
MsgBox notAct(2, 2) 'it returns a 0

It vba doesn't appreciate the ReDim notAct(2, 2). is there a way to get the redim working in a 2d-array. I want to return the value when notAct(2, 2) gets 1.


Solution

  • You need to dim the array without dimensions first:

    Dim notAct() as Integer
    

    The you can redimension it:

    Redim notAct(1 to 20, 1 to 43) as Integer
    

    Note that redimensioning an array will cause it to lose any data currently stored. To preserve the data, you need to use the Preserve keyword:

    Redim Preserve notAct(1 to 20, 1 to 2) as Integer
    

    Note that when using the Preserve keyword you can only change the last dimension's bounds.