I have a region of data with a variable number of rows and columns. How would someone create a master arraylist and a temporary arraylist that can grab all the values of each row and then store that into the master arraylist and then clear the temporary arraylist? I don’t know exactly how many items will go into either the master or the temporary and when this report is run on another day the number of items will likely be different so it needs to be flexible.
Sub arrayListsInArrayList() Dim MasterArrayList As Object Dim tempArrayList As Object Dim rowIndexer As Integer, rowCounter As Integer Dim colIndexer As Integer, colCounter As Integer Set MasterArrayList = CreateObject("System.Collections.ArrayList") Set tempArrayList = CreateObject("System.Collections.ArrayList") rowCounter = Range("A1", Range("A1").End(xlDown)).Count colCounter = Range("A1", Range("A1").End(xlToRight)).Count For rowIndexer = 0 To rowCounter - 1 tempArrayList.Clear For colIndexer = 0 To colCounter - 1 tempArrayList.Add Range("A1").Offset(rowIndexer, colIndexer).Value Next colIndexer MasterArrayList.Add tempArrayList Next rowIndexer End Sub
This code “works” but since the same-named tempArrayList is added so many times, I end up with repeated items. Is there a way to dynamically name the temporary arraylist? ie tempArrayList1, 2, etc.?
I think if simply adding ArrayLists of individual row values to a shared parent
ArrayList, and clearing the tempArrayList in between, you can use
clone method (this prevents the loss of values in parent when temp is cleared). The below ignores the source being jagged but you could use helper functions to determine instead last column per row.
Assuming empty elements are fine:
Option Explicit Public Sub testList() Dim src(), r As Long, c As Long Dim tempList As Object, masterList As Object Set tempList = CreateObject("System.Collections.ArrayList") Set masterList = CreateObject("System.Collections.ArrayList") src = Range("A1:C3").Value For r = LBound(src, 1) To UBound(src, 1) For c = LBound(src, 2) To UBound(src, 2) tempList.Add src(r, c) Next masterList.Add tempList.Clone tempList.Clear Next Stop End Sub