Excel VBA Populate Array: Step-by-Step Guide
In this article
To populate an array in Excel VBA, you declare the array with Dim, size it (either with fixed bounds or ReDim), then assign values to each element by index, starting at 0 unless you set Option Base 1. For a fast one-line fill from a worksheet range, use myArray = Range("A1:A10").Value. Everything else is a variation on those two ideas: looping to fill, filling from a range, filling from another array, and growing the array as you go.
What You'll Need
- Excel with the Developer tab enabled (File > Options > Customize Ribbon, tick Developer in the right-hand list). Menu labels can differ slightly by version, device or region.
- A workbook saved as
.xlsmif you want the macro to survive closing Excel. The older.xlsworks too, but.xlsxwill strip the code. - Basic comfort with the VBA editor: Alt+F11 opens it, Ctrl+G opens the Immediate window for quick tests, F8 steps through code line by line.
- Some data to work with, even if it is a scratch sheet of numbers in A1:A10.
Step-by-Step
Create a module. Press Alt+F11 to open the editor, then use Insert > Module. Code written in a sheet module also works, but a standard module keeps the macro visible in the Macro list and easy to call from anywhere.
Declare the array. At the top of the procedure, type
Dim nums(1 To 5) As Longfor a fixed-size array of five numbers, orDim names() As Stringfor a dynamic one you will size later. Fixed bounds are the simplest choice when you know exactly how many items you need.Fill it element by element. Assign values by index:
nums(1) = 10 nums(2) = 20 nums(3) = 30 nums(4) = 40 nums(5) = 50Remember that a plain
Dim nums(5)without1 Togives you six slots numbered 0 to 5, not five. Off-by-one errors from this are the single most common array bug in VBA.Or fill it with a loop. For anything repetitive, a
Forloop is cleaner than typing each line:Dim i As Long For i = LBound(nums) To UBound(nums) nums(i) = i * 10 Next iLBoundandUBoundreturn the first and last valid indexes, so the loop keeps working if you resize the array later. Never hard-code the upper limit if you can useUBound.Fill from a worksheet range in one shot. This is the fastest method and the one to prefer for large data sets. Assigning a range's
Valueto a Variant produces a two-dimensional array automatically:Dim data As Variant data = Range("A1:C100").Valuedatanow holds 100 rows and 3 columns, indexeddata(row, column)starting at 1. This is a genuine 2D array even when the range is a single column, so refer todata(5, 1), notdata(5). Assigning to a Variant is essential; a declaredDouble()array will not accept a range directly.Size a dynamic array before filling. If you declared
Dim vals() As Double, you must callReDimbefore touching any element:ReDim vals(1 To 50) vals(1) = 3.14Use
ReDim Preserveonly when you need to keep existing contents while changing the last dimension. It is slow in a loop because VBA copies the whole array each time.Grow the array from a loop safely. When the count is unknown up front, the efficient pattern is to collect into a large buffer and shrink once at the end:
Dim buf() As String, n As Long ReDim buf(1 To 1000) For n = 1 To 1000 If Cells(n, 1).Value <> "" Then buf(n) = Cells(n, 1).Value End If Next n ReDim Preserve buf(1 To n - 1)Alternatively, count matching rows first with
WorksheetFunction.CountA, then size the array exactly and fill it. Both avoid callingReDim Preserveinside the loop.Read the values back to prove it worked. Write results out with
Debug.Printto the Immediate window, or push the array back onto a sheet in a single statement:Range("E1").Resize(UBound(buf), 1).Value = Application.Transpose(buf)Application.Transposeflips a one-dimensional array into a column. For arrays longer than about 65,536 elements it fails with a type mismatch, so for very large sets loop through and write row by row, or keep everything as 2D from the start.Fill an array from another array or a function.
Array(1, 2, 3)returns a Variant containing a one-dimensional array in one expression, handy for short lists.Split("a,b,c", ",")returns a zero-based String array, which catches people out because it starts at 0 regardless ofOption Base. Copying between arrays needs either a loop orVariantassignment; VBA has no single built-in whole-array copy for typed arrays.
Common Mistakes
- Forgetting
ReDimon a dynamic array. You get run-time error 9, subscript out of range, the moment you assign an element. - Assuming a range array starts at 0. Arrays read from a worksheet start at 1 for both dimensions. Looping from 0 silently skips the first item or errors.
- Treating a 2D range array as 1D.
data(i)on a range-derived array raises a wrong-number-of-dimensions error. Always use two indexes. - Declaring the destination as a typed array.
Dim d() As Double: d = Range("A1:A10").Valuefails. UseVariantas the destination, then convert if you need to. - Using
ReDim Preservein a tight loop. It works but it is dramatically slower than a single resize at the end, especially past a few thousand items. - Confusing
Option Base 1effects. It changesDim a(5)to five elements, but it does not changeSplitor range-derived arrays. - Leaving the array as text. Values read from cells come through as Variants that may hold strings; wrap with
CDblorCLngbefore doing arithmetic.
Tips
- Use
LBoundandUBoundeverywhere instead of hard-coded limits; the code then survives resizing. - Add
Option Explicitat the top of the module so misspelled array names are caught at compile time. - For big data, reading a range into an array once and looping in memory is far faster than reading cell by cell in a loop. Cell access is the slow part, not the array.
- Keep a single array as 2D from the start when the data may come from a range later; it avoids conversion headaches.
- Bind each element's type explicitly with
As Long,As StringorAs Doublewhere you know it, rather than relying on Variants throughout.
Troubleshooting
Error 9, subscript out of range. You are reading or writing an index outside LBound to UBound. Print both bounds to the Immediate window with Debug.Print LBound(a), UBound(a) and compare them with the index your loop uses.
Error 13, type mismatch on ReDim or assignment. The destination array is typed (for example Double()) but the source is a Variant from a range or Split. Redeclare the destination as Variant.
Wrong number of dimensions. You built a 1D array but indexed it with two values, or the reverse. Range assignments always produce 2D; Array() and Split always produce 1D.
The array is empty after the macro runs. Check that the loop actually executed: a For loop over an empty range runs zero times, and ReDim Preserve buf(1 To 0) is invalid. Guard with If n > 0 Then before resizing.
Output lands in a row instead of a column. Transpose converts rows to columns and vice versa. Swap it, or use Resize(1, UBound(a)) for a horizontal write.
The macro vanished. The workbook was saved as .xlsx. Save as .xlsm and the code will persist. Also check that macros are enabled in the Trust Center.
If That Did Not Work
Strip the code back to a minimal test: declare a three-element array, fill it with the constants 1, 2, 3, and print each element with Debug.Print. Once that runs, add your range read, then your loop, then your write-back one stage at a time, pressing F8 to step. The failure will show up at the exact stage that introduced it instead of somewhere in the middle of a finished procedure.
Frequently Asked Questions
Does a VBA array start at 0 or 1?
By default it starts at 0, so Dim a(5) holds six elements. Add Option Base 1 above the procedure to make it start at 1. Arrays filled from a worksheet range always start at 1 regardless of that setting.
Can I fill an array directly from a range?
Yes. Assign the range's Value to a Variant: data = Range("A1:C10").Value. The result is a two-dimensional array indexed (row, column), starting at 1.
How do I add items to an array one at a time?
Use ReDim Preserve to extend it: ReDim Preserve a(UBound(a) + 1). It works, but each call copies the entire array, so for anything beyond a few hundred items fill a pre-sized buffer and trim at the end.
Why does my array only hold the last value?
You are almost certainly assigning to the whole array name instead of an indexed element. a = Cells(i, 1).Value overwrites everything; a(i) = Cells(i, 1).Value fills one slot.
What is the fastest way to load a lot of cells?
One range-to-Variant assignment, then loop in memory. Reading cells one at a time inside a loop is the bottleneck, not the array itself.
Can I resize an array without losing its contents?
Yes, with ReDim Preserve, but only the last dimension can change, and only for dynamic arrays declared with empty parentheses. Typed fixed-size arrays cannot be resized at all.