简体   繁体   中英

Reusing 2D array in VBA Excel?

New here, and new to VBA and programming in general.

I am trying to reuse multiple arrays (through a loop), but I assume I need to clear them out before I reuse them? I have tried searching through the questions, but I can't find a solution, or frankly can't understand the solutions if they work.

Dim WS As Worksheet

For Each WS In Worksheets
    If Right(WS.Name, 4) = "Data" Then Comp = Comp + 1
Next WS

Dim CompArray(10, 50) As Variant
Dim RatesArray(10, 1 To 50) As Variant
Dim IndexArray(10, 50) As Variant
Dim ShortIndexArray(10) As Long
Dim MRow, DRow, FRow, RRow, Col As Long
Dim LastCol, LastRow As Long

MRow = 4
LastRow = Cells(Rows.Count, 1).End(xlUp).Row


Do Until MRow > LastRow

    '**** MY CODE ****

''''***!!!*** Trying to Clear the array and reuse with the same dimensions for each loop ***!!!***
' not working

''Erase CompArray, RatesArray, IndexArray, ShortIndexArray
''ReDim CompArray(10, 50)
''ReDim RatesArray(10, 1 To 50)
''ReDim IndexArray(10, 50)
''ReDim ShortIndexArray(10)

MRow = MRow + 6 + Comp
Loop




End Sub

so when I go to the next step of the main loop, the arrays that I want to use have the same information. I want to keep the same names and dimensions of the arrays, but just clear out the contents. It sounds simple to me, but I have no idea how to do this.

I tried erasing and redim-ing (that was a solution to a similar problem on here) but it didnt work, it actually was saying I was declaring the arrays twice.

I also tried dim-ing the arrays while already in the loop. That didn't work either.

Any help would be appreciated!

Thanks.

If you want to reuse an array then you shouldn't specify the dimensions when you first declare it

Dim CompArray() As Variant

Then when you want to initialize it you use the keyword Redim

ReDim CompArray(10, 50)

If you redim your array again then you will loose any data already stored in it, unless you use the Preserve keyword

ReDim Preserve CompArray(10, 60)

And if you're redimensioning your array and preserving the content then you can only change the last dimension

so ReDim Preserve CompArray(10, 80) will work as you're changing the last element. ReDim Preserve CompArray(100, 80) will cause an error as you're attempting to change the first element and preserve the data.

ReDim CompArray(100, 800) will work fine, but you will lose all your currently stored data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM