VBA course · Lesson 15 of 33

Arrays in VBA: static, dynamic and fast range processing

Store many values in one variable with VBA arrays: static and dynamic arrays, ReDim Preserve, 2-D arrays and reading a whole range into memory for speed.

Intermediate 18 min read

A normal variable holds one value: one price, one name, one date. An array is a variable that holds a whole list of values under one name, each in its own numbered slot. Instead of declaring price1, price2, price3 and so on, you declare one array prices and refer to prices(1), prices(2), prices(3).

Arrays matter for two reasons. First, they make code shorter when you work with lists, because you can loop over the slots with a For loops: For...Next and For Each loop. Second, and this is the big one in Excel, they make code fast. Reading a range of 50,000 cells into an array, working on it in memory and writing it back in one go can be a hundred times quicker than touching the cells one by one. By the end of this lesson you will know how to do exactly that.

Declaring a static array

A static array has a fixed size that you decide when you write the code. You give the size in brackets after the name:

VBA
Option Explicit

Sub StaticArrayDemo()
    Dim months(1 To 5) As String
    Dim i As Long

    months(1) = "January"
    months(2) = "February"
    months(3) = "March"
    months(4) = "April"
    months(5) = "May"

    ' Print every slot to the Immediate window (Ctrl+G to show it)
    For i = 1 To 5
        Debug.Print i, months(i)
    Next i
End Sub
A static array of five month names

Dim months(1 To 5) As String creates five slots numbered 1 to 5, each able to hold a String. The numbers are called indexes (or subscripts). You read and write a slot exactly like a normal variable, just with the index in brackets.

Where do indexes start?

If you write only the upper bound, as in Dim months(5) As String, VBA starts counting at 0, so you actually get six slots: 0, 1, 2, 3, 4 and 5. This surprises almost everyone the first time. You can change the default with Option Base 1 at the top of a module, but it is clearer to always write both bounds: (1 To 5) or (0 To 4). Then nobody has to guess.

Tip. Write Dim x(1 To 12) rather than Dim x(12). It costs four characters and removes a whole class of off-by-one bugs.

LBound and UBound

Hard-coding For i = 1 To 5 is fragile: if the array later grows to six items, the loop silently skips one. Use the functions LBound (lower bound) and UBound (upper bound) instead. They return the first and last index of an array, whatever they are.

VBA
Option Explicit

Sub BoundsDemo()
    Dim regions(0 To 3) As String
    Dim i As Long

    regions(0) = "North"
    regions(1) = "South"
    regions(2) = "East"
    regions(3) = "West"

    Debug.Print "First index: "; LBound(regions)   ' 0
    Debug.Print "Last index: "; UBound(regions)    ' 3
    Debug.Print "Count: "; UBound(regions) - LBound(regions) + 1

    For i = LBound(regions) To UBound(regions)
        Debug.Print regions(i)
    Next i
End Sub
Looping safely with LBound and UBound

The count of items is always UBound - LBound + 1. Memorise that formula; you will use it constantly.

Quick arrays with Array() and Split()

Typing one assignment per slot gets tedious. The Array function builds an array from a list of values in one line. It returns a Variant that contains an array, so the receiving variable must be declared As Variant. Arrays created with Array start at index 0 (unless you used Option Base 1).

The Working with text (strings) in VBA function Split cuts a text into pieces at a delimiter and returns a 0-based array of strings. It is perfect for lists stored in one cell, such as "Ana;Ben;Chloe".

VBA
Option Explicit

Sub ArrayAndSplit()
    Dim vatRates As Variant
    Dim staff() As String
    Dim i As Long

    vatRates = Array(0.24, 0.13, 0.06)        ' standard, reduced, super-reduced
    Debug.Print "Standard rate: "; vatRates(0)

    staff = Split("Ana;Ben;Chloe;Dimitri", ";")
    For i = LBound(staff) To UBound(staff)
        Debug.Print i, staff(i)
    Next i
    ' 0 Ana, 1 Ben, 2 Chloe, 3 Dimitri
End Sub
Building arrays from a list of values and from text

The opposite of Split is Join, which glues the items of a 1-D string array back into one text: Join(staff, ", ") gives Ana, Ben, Chloe, Dimitri.

Dynamic arrays and ReDim

Often you do not know the size in advance: how many invoices are overdue, how many files are in a folder. A dynamic array is declared with empty brackets and sized later with ReDim:

VBA
Dim overdue() As String
ReDim overdue(1 To 10)

You can run ReDim as often as you like, with numbers calculated while the macro runs. But by default ReDim wipes the contents. To resize and keep what is already stored, add Preserve:

VBA
Option Explicit

Sub CollectOverdue()
    Dim ws As Worksheet
    Dim overdue() As String
    Dim count As Long
    Dim r As Long

    Set ws = ThisWorkbook.Worksheets("Invoices")
    count = 0

    ' Data: A = invoice number, C = due date, D = status, starting in row 2
    For r = 2 To ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
        If ws.Cells(r, "D").Value <> "Paid" And ws.Cells(r, "C").Value < Date Then
            count = count + 1
            ReDim Preserve overdue(1 To count)
            overdue(count) = ws.Cells(r, "A").Value
        End If
    Next r

    If count = 0 Then
        MsgBox "No overdue invoices."
    Else
        MsgBox count & " overdue: " & Join(overdue, ", ")
    End If
End Sub
Collecting overdue invoice numbers into a growing array

Each time an overdue invoice is found, the array grows by one slot and the new number goes into the last slot. Note the check count = 0 at the end: if nothing was found, the array was never sized, and calling Join or UBound on an unsized array raises run-time error 9, Subscript out of range.

The ReDim Preserve limits

ReDim Preserve has two rules that trip people up:

  • With Preserve you can only change the last dimension of a multi-dimensional array. For a 2-D array (1 To rows, 1 To cols) you can add columns but not rows. The usual workaround is to size the array as (1 To cols, 1 To rows) while collecting, or to size it once at the maximum possible size and track a counter.
  • You cannot change the lower bound with Preserve.

ReDim Preserve also copies the whole array into new memory each time. Growing by one slot in a loop of 100,000 rows gets slow. A faster pattern is to ReDim once to the largest possible size (for example the number of data rows), fill only what you need, and shrink once at the end.

Two-dimensional arrays

An array can have more than one dimension. A 2-D array is like a little worksheet in memory: the first index is the row, the second is the column.

VBA
Dim sales(1 To 3, 1 To 4) As Double   ' 3 regions x 4 quarters
sales(2, 3) = 18250                     ' region 2, quarter 3

To loop over a 2-D array you nest two loops, and you ask for the bounds of each dimension by passing the dimension number as the second argument: UBound(sales, 1) is the last row, UBound(sales, 2) the last column.

Reading a range into an array

This is the most useful array technique in Excel VBA. Assigning a multi-cell range's .Value to a Variant variable copies all the values into a 2-D array in one operation:

VBA
Dim data As Variant
data = Range("A2:D501").Value

The resulting array is always 1-based in both dimensions, regardless of Option Base, and always 2-D, even for a single column. So data(1, 1) is the value from A2 and data(500, 4) is the value from D501. You can then loop through data without touching the sheet, and at the end write a whole array back with one assignment: Range("E2:E501").Value = results.

Here is a full example. The sheet Sales holds a list of orders, and we want to add a commission in column E: 5% of the amount, but 8% for orders of 10,000 or more.

ABCDE
1OrderRepRegionAmountCommission
2S-1001AnaNorth4200
3S-1002BenSouth12500
4S-1003ChloeNorth8000
5S-1004AnaEast10000
6S-1005DimitriWest950

Before: the Sales sheet with an empty Commission column

VBA
Option Explicit

Sub AddCommission()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim amounts As Variant
    Dim result() As Double
    Dim i As Long

    Set ws = ThisWorkbook.Worksheets("Sales")
    lastRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
    If lastRow < 3 Then Exit Sub   ' needs at least two data rows (see the single-cell note below)

    ' 1. Read the whole Amount column in one go
    amounts = ws.Range("D2:D" & lastRow).Value

    ' 2. Prepare an output array with the same shape: n rows x 1 column
    ReDim result(1 To UBound(amounts, 1), 1 To 1)

    ' 3. Work in memory
    For i = 1 To UBound(amounts, 1)
        If amounts(i, 1) >= 10000 Then
            result(i, 1) = amounts(i, 1) * 0.08
        Else
            result(i, 1) = amounts(i, 1) * 0.05
        End If
    Next i

    ' 4. Write all results back in one go
    ws.Range("E2:E" & lastRow).Value = result
End Sub
Calculating commission for every row in memory
ABCDE
1OrderRepRegionAmountCommission
2S-1001AnaNorth4200210
3S-1002BenSouth125001000
4S-1003ChloeNorth8000400
5S-1004AnaEast10000800
6S-1005DimitriWest95047.5

After: one write fills the whole Commission column

Notice that the output array is declared 2-D with one column, (1 To n, 1 To 1). A 1-D array written to a vertical range does not work as you might hope: Excel treats a 1-D array as a row, so every cell in the column would receive the first value. If you have a 1-D array and need it in a column, either build it 2-D from the start or use Application.Transpose (which has limits on very large arrays, so building it 2-D is safer).

The program touches the worksheet exactly twice: once to read, once to write. With 100,000 rows the cell-by-cell version can take many seconds; this version usually finishes in well under one. Make your macros fast: speed optimization in VBA goes further into speed.

The single-cell trap

If the range is a single cell, .Value returns just that value, not an array. Then UBound(amounts, 1) fails with a type mismatch. That is why the example exits when there are fewer than two data rows. In real code you can handle it explicitly:

VBA
Option Explicit

Function RangeToArray(rng As Range) As Variant
    Dim one(1 To 1, 1 To 1) As Variant
    If rng.Cells.Count = 1 Then
        one(1, 1) = rng.Value
        RangeToArray = one
    Else
        RangeToArray = rng.Value
    End If
End Function
Making sure you always get a 2-D array

Call it with amounts = RangeToArray(ws.Range("D2:D" & lastRow)) and you get a 2-D array in every case. Functions like this are covered in Functions and Subs: parameters, ByVal, ByRef and return values.

Clearing an array with Erase

Erase resets an array. For a static array it sets every slot back to its default (0, empty text, Empty); the size stays. For a dynamic array it frees the memory completely, so you must ReDim it again before using it.

VBA
Erase overdue        ' dynamic: now unsized again

Arrays of Variants and checking for arrays

When you do not know the data types in a range (text, numbers and dates mixed), the array must be Variant. That is the normal case for range arrays. You can test whether a variable currently holds an array with IsArray(x), which is handy after reading a range that might be one cell.

Note. On a Mac arrays behave identically. The only practical difference is speed: Excel for Mac is generally slower at cell-by-cell access, so the read-into-array technique pays off even more there.

Common mistakes

  • Forgetting that Dim x(5) has six slots. Write both bounds.
  • Using an array before sizing it. A dynamic array needs ReDim before the first assignment, or you get error 9.
  • ReDim without Preserve when you wanted to keep the data: everything is wiped.
  • Trying to ReDim Preserve the first dimension of a 2-D array: error 9. Only the last dimension can grow.
  • Assuming range arrays start at 0. Arrays from Range.Value always start at 1.
  • Writing a 1-D array to a column. Excel repeats the first value; use a 2-D (n, 1) array.
  • Resizing the target range wrongly. The range you write to must have the same number of rows and columns as the array. A quick way is ws.Range("E2").Resize(UBound(result, 1), UBound(result, 2)).Value = result.

Check yourself

1. How many slots does Dim scores(4) As Long create (without Option Base 1)?

2. You read Range("A2:C100").Value into a Variant called data. What is the first value?

3. Which statement grows a dynamic array by one slot without losing its contents?

4. With ReDim Preserve on a 2-D array, which dimension can you change?

5. Why is reading a range into an array usually much faster than looping through the cells?