


In Excel we spend a lot of time repeating simple tasks. Skill level: Intermediate The Power of VBA Loops This article explains how the loop works to repeat actions on a collection of items, which saves us a ton of time with our jobs. When you click debug, the error will be highlighted showing that the first dimension in the array is not the same as the first dimension when the array size was originally declared.Bottom line: The For Next Loops are some of the most powerful VBA macro coding techniques for automating common tasks in Excel. You can only resize the last dimension of an Array if want to keep the original data in the Array with Re-Dim Preserve.

'populate the array with additional values When you redeclare the array, you will lose any data previously held in the array unless you use the ReDim Preserve Statement. You can resize an array using ReDim ( learn more). Ws_Destination.Range("A1").Offset(rw,col).Value = wsData(rw, col)Įnd Sub Resizing using ReDim and Re-Dim Preserve ' populate the destination sheet from the array Set ws_Destination = Worksheets("Sheet2") WsData(rw, col) = ws_Source.Range("A2").Offset(rw, col).Value

'get the information from the source sheet and populate the arrayįor rw = LBound(wsData, 1) To UBound(wsData, 1)įor col = LBound(wsData, 2) To UBound(wsData, 2) The code below will populate a 2D array from an Excel worksheet and then populate a different sheet with the data. Your Excel spreadsheet should then be populated as follows. 'loop through the array and populate ExcelĬells(rw + 1, col + 1).Value = intA(rw, col) The code below will populate a 2D array, and then populate the rows and columns of a worksheet with the values in the array.
