Excel VBA Variant Arrays: A Step-by-Step Guide
In this article
A Variant array in Excel VBA is simply an array that has not been typed as a specific data type, so each element can hold a number, a string, a date, an error value, or even another array. You use one whenever you need to move a whole range into memory, loop over rows quickly, resize the array as you go with ReDim, or hand a block of values back to a worksheet in one shot. Nothing needs installing: open the Visual Basic Editor with Alt+F11 (Option+F11 on a Mac) and you can follow every step below.
What You'll Need
- Excel with macros enabled (desktop Windows or Mac versions; the steps are written for the desktop app, not Excel for the web, which cannot run VBA).
- A workbook saved as .xlsm or .xlsb so your code survives closing the file. A macro-enabled workbook is required before you save.
- Access to the Visual Basic Editor: Alt+F11 on Windows, Option+F11 on a Mac. On a Mac you may also need to allow macros in the Trust Center.
- A sheet with some sample data, ideally a small table with a header row and a few rows underneath.
Step-by-Step
- Open the editor and add a module. Press Alt+F11, then in the Project Explorer right-click your workbook name and choose Insert > Module. If the Project Explorer is hidden, use View > Project Explorer. Code goes in a standard module, not in a sheet module, unless you specifically need sheet events.
- Declare the array. Start with the simplest form:
Dim data As Variant. Note thatDim data() As Variantdeclares a dynamic array, which you resize later. Both are Variants; the difference is whether the size is fixed at declaration. - Load a range into the array in one line. With a table on Sheet1 covering A1:C10, write
data = Range("A1:C10").Value. This creates a two-dimensional Variant array with the same boundaries as the range. If the range is a single cell, you get a scalar rather than an array, so guard against that case. - Remember the lower bounds. A range-loaded array is always 1-based in both dimensions, so the first element is
data(1, 1), notdata(0, 0). That is the single most common source of confusion, and it differs from arrays you build yourself, which default to 0 unless you useOption Base 1. - Loop over the values. Use nested loops and the
LBoundandUBoundfunctions rather than hard-coded numbers so the code still works when the table grows. For example,For r = LBound(data, 1) To UBound(data, 1)andFor c = LBound(data, 2) To UBound(data, 2). Reading and writing cells directly inside a loop is slow; working on the in-memory array is fast. - Process or transform the data. Inside the loops you can test and rewrite elements, for instance multiply every value in column 3 by a factor, or replace blanks with zero. Because the array is Variant, you can store a string in one element and a number in another without a type mismatch.
- Write the array back to the sheet in one operation. Size a destination range to match the array and assign:
Range("E1").Resize(UBound(data, 1), UBound(data, 2)).Value = data. This is much faster than writing cell by cell, and it preserves the two-dimensional shape. - Resize a dynamic array when needed. If you declared
Dim results() As Variant, useReDim results(1 To 100)to set the size. To grow while keeping existing values, useReDim Preserve. Only the last dimension can be preserved, and each Preserve call copies the whole array, so it is slow in a tight loop. - Build a one-dimensional array from scratch. Declare, resize, then fill by index:
ReDim names(0 To 2), thennames(0) = "Alpha", and so on. A one-dimensional array assigned to a single column of cells should be transposed withApplication.WorksheetFunction.Transposeor assigned carefully, because Excel treats a flat array as a row. - Run and inspect. Press F5 with the cursor inside the procedure, or use Run > Run Sub. Use the Locals window (View > Locals) or add a
Debug.Printline and check the Immediate window to confirm the bounds and a few values before trusting the output. - Clean up and save. Release the array with
Erase datawhen you are done with a large one, and save the workbook as macro-enabled. Test on a copy of your data first, because a bad write-back overwrites cells with no undo.
Common Mistakes
Assuming 0-based indexing. Arrays loaded from a range start at 1. Looping from 0 either errors at the lower bound or silently reads the wrong cell.
Forgetting that a single-cell range is not an array. Range("A1").Value gives you one value, so indexing it fails. Check the cell count first or handle both cases.
Using ReDim Preserve on the wrong dimension. VBA only preserves the last dimension, and with a two-dimensional array from a range you often want to add rows, which is the first dimension. Build a new array or transpose your layout instead.
Writing back to a mismatched size. If the destination Resize does not match the array exactly, you either get a run-time error or leave stale cells untouched.
Mixing up rows and columns. A range array is indexed (row, column). Swapping the loop order produces plausible-looking but wrong results rather than an error.
Leaving Option Explicit off. A misspelled array name silently creates a new empty Variant instead of failing, so always put Option Explicit at the top of the module.
Tips
- Use
LBoundandUBoundwith the dimension number (1 for rows, 2 for columns) instead of typing sizes. - Read the whole range once, work in memory, and write once. The speed difference on large tables is dramatic.
- To pull a range with a known size,
Range("A1").CurrentRegion.Valuegrabs the contiguous block including headers. - Use
IsArrayto check whether you actually got an array before indexing. - For very large loops, set
Application.ScreenUpdating = Falseand restore it at the end so the screen does not redraw on every change. - Keep a small helper that returns row and column counts from an array, so your procedures stay readable.
- Test on a duplicate worksheet and keep a backup copy; there is no undo for VBA writes.
Troubleshooting
Run-time error 9, subscript out of range. Your index is outside the array's bounds. Print LBound and UBound for both dimensions to see the real limits, and remember range arrays start at 1.
Type mismatch on assignment. Something you are putting into the array, or the destination cell, does not accept it. A Variant array holds mixed types fine, but a formula string starting with the wrong character or an error value can trip the write-back. Write to a test range and inspect the offending element.
Blank or zero results. Usually the array was never loaded, or a single-cell range returned a scalar and the later indexing quietly failed under a missing Option Explicit. Step through with F8 and watch the array in the Locals window.
Wrong data appears shifted by one row or column. An off-by-one in a loop, or a 1-based array looped from 0. Confirm the starting index for each dimension.
Macro will not run. Check that the file is macro-enabled, that macros are allowed in the Trust Center, and on a Mac that the correct editor shortcut was used. If the code sits in a sheet module when it should be in a standard module, the procedure may not appear in the macro list.
It runs slowly or seems frozen. A Preserve inside a loop or cell-by-cell writing is the usual cause. Reduce the number of resizes and batch the output. If it is still slow, check for a huge used range being pulled in by UsedRange, which can include empty formatted cells.
Frequently Asked Questions
What exactly is a Variant array in VBA?
An array declared without a specific element type, so each element can hold any value: number, text, date, error or another array. It is the natural type for data read from a worksheet range, because a range can contain mixed types.
Why does my range array start at 1 instead of 0?
When you assign a range's Value to a Variant, VBA builds a 1-based two-dimensional array matching the range. Arrays you size yourself with Dim x(5) start at 0 unless you use Option Base 1.
Is a Variant array slower than a typed array?
It uses a little more memory per element, but for typical spreadsheet work the difference is negligible. Reading a range once into a Variant array and writing it back in one go is far faster than touching cells one at a time.
Can I add rows to an array with ReDim Preserve?
Only if rows are the last dimension. With a standard range array, rows are the first dimension, so you cannot preserve them. Build a new array of the target size, copy the old values across, then assign it back.
Why is my single-cell range not behaving like an array?
A one-cell range returns a single value rather than an array. Check Range(...).Cells.Count or use IsArray before you index, and handle the single-value case separately.
Do I need to clear the array when I am done?
No for small arrays, but for very large ones Erase releases the memory and sets the variable to an uninitialised state, which is tidy and avoids surprises if the same variable is reused later in the procedure.