To declare an array in VBA, use the Dim statement with parentheses: Dim MyArray(1 To 10) As Integer for a fixed-size array, or Dim MyArray() As Integer followed by ReDim MyArray(1 To 10) for a dynamic array. This creates a variable that can hold multiple values under one name, indexed by numbers. Below, you’ll find the full syntax, the differences between fixed and dynamic arrays, how to size them, and common pitfalls to avoid.
What Is an Array and Why Use One?
An array is a single variable that stores a collection of values, each accessed by an index. Instead of declaring Dim Score1 As Integer, Dim Score2 As Integer, and so on, you declare one array and fill it with scores. Arrays are essential when you work with lists, ranges, or any data that comes in rows or columns. In VBA, arrays can hold any data type—Integer, String, Variant, even objects—and can be one-dimensional (like a list) or multi-dimensional (like a table).
Declaring a Fixed-Size Array
A fixed-size array has a set number of elements that you specify at declaration. The syntax is:
Dim MyArray(1 To 5) As String
Dim AnotherArray(0 To 9) As Integer ' 10 elements, indices 0 through 9
Dim SimpleArray(5) As Double ' indices 0 to 5, 6 elements total
Note that if you specify only an upper bound (e.g., Dim A(5) As Integer), VBA uses the default lower bound of 0, so it creates 6 elements (0 through 5). You can change the default lower bound with Option Base 1 at the top of the module, but it’s clearer to always specify both bounds using 1 To n or 0 To n.
Declaring a Dynamic Array
A dynamic array can be resized during runtime when you don’t know the size in advance. Declare it with empty parentheses, then use ReDim to set the size:
Dim MyData() As Variant
ReDim MyData(1 To 100)
' ... fill the array ...
ReDim Preserve MyData(1 To 200) ' resize while keeping existing values
The Preserve keyword keeps the data already in the array when you resize it. Without Preserve, ReDim clears all values. You can also declare and size a dynamic array in one line using ReDim directly, but it’s common to declare with Dim first for clarity.
Choosing Between Fixed and Dynamic Arrays
Use a fixed array when the size is known and won’t change—for example, days of the week (7 elements). Use a dynamic array when the size depends on user input, a loop, or data read from a worksheet. Dynamic arrays are more flexible but require ReDim calls, which can be slower if done repeatedly. A common pattern is to read a range into a Variant array, which is automatically sized:
Dim Data As Variant
Data = Range("A1:C10").Value ' creates a 2D array (1 to 10, 1 to 3)
This is often faster than looping cell by cell. However, note that this creates a 1-based, two-dimensional array regardless of the range’s shape.
Multi-Dimensional Arrays
You can declare arrays with multiple dimensions, like a table with rows and columns:
Dim Matrix(1 To 3, 1 To 3) As Integer
Dim Cube(1 To 2, 1 To 2, 1 To 2) As String ' 3D array
Access elements with multiple indices: Matrix(1, 2) = 10. The first index is the row, the second is the column. For dynamic multi-dimensional arrays, use ReDim with multiple bounds:
Dim Table() As Integer
ReDim Table(1 To 10, 1 To 5)
When using ReDim Preserve on a multi-dimensional array, you can only change the last dimension; changing any other dimension will cause an error.
Common Problems and How to Avoid Them
- Subscript out of range (Error 9): Accessing an index outside the declared bounds. Always check
LBoundandUBound. - Forgetting to ReDim a dynamic array: Using a dynamic array without sizing it first raises an error. Always
ReDimbefore assigning. - Losing data with ReDim: Without
Preserve,ReDimclears the array. UseReDim Preservewhen you need to keep values. - Confusing lower bound: By default, VBA uses 0 as the lower bound unless you specify
1 To nor useOption Base 1. This can cause off-by-one errors. - Declaring arrays inside loops: If you declare a fixed array inside a loop, it is re-created each iteration, which is inefficient. Declare it once outside the loop.
To find the size of an array, use LBound(MyArray) and UBound(MyArray). For multi-dimensional arrays, specify the dimension: UBound(MyArray, 2).
Frequently Asked Questions
What is the difference between Dim and ReDim?
Dim declares a variable and, for fixed arrays, sets its size at compile time. ReDim is used only for dynamic arrays to set or change the size at runtime. You can use Dim to declare a dynamic array with empty parentheses, then ReDim to size it later.
How do I declare an array of strings?
Use Dim MyStrings(1 To 5) As String for a fixed array, or Dim MyStrings() As String and then ReDim MyStrings(1 To 5) for a dynamic one. Assign values like MyStrings(1) = "Hello".
Can I declare an array without specifying the size?
Yes, that’s a dynamic array: Dim MyArray() As Integer. You must later use ReDim to set its size before you can assign values to its elements.
What does ReDim Preserve do?
It resizes an array while keeping the existing values in the elements that remain. For example, if an array has 10 elements and you use ReDim Preserve MyArray(1 To 20), elements 1 through 10 keep their values, and 11 through 20 are empty.
How do I declare a 2D array in VBA?
Use a comma inside the parentheses: Dim MyTable(1 To 3, 1 To 4) As Integer. This creates a 3-by-4 table. Access elements with two indices: MyTable(1, 2) = 5.
Why do I get a “Subscript out of range” error?
This error occurs when you try to access an array element with an index that is less than the lower bound or greater than the upper bound. For example, if you declared Dim A(1 To 5) As Integer, accessing A(6) will trigger this error. Always verify the bounds with UBound and LBound before accessing.
Practical Example: Reading a Range into an Array
A common use is to read a worksheet range into an array for fast processing. Here’s a complete macro that sums the values in a range:
Sub SumRange()
Dim Data As Variant
Dim Total As Double
Dim i As Long, j As Long
' Read the range into a 2D array
Data = Range("A1:C10").Value
' Loop through each element
For i = 1 To UBound(Data, 1)
For j = 1 To UBound(Data, 2)
Total = Total + Data(i, j)
Next j
Next i
MsgBox "Total: " & Total
End Sub
Remember to save a copy of your workbook before running any macro, as macros cannot be undone with Ctrl+Z. This example assumes the range contains numbers; if it contains text, the addition will cause a type mismatch error.
Performance and Best Practices
Arrays are faster than working directly with worksheet cells because they avoid repeated COM calls. For large datasets, read the entire range into a Variant array, process it in memory, and write back in one operation. When using dynamic arrays, minimize the number of ReDim Preserve calls by estimating the size or using a collection and then converting to an array. Also, always specify the lower bound explicitly to avoid confusion, and use Long for array indices if you expect more than 32,767 elements (the limit for Integer).
Related
- Importance of Data Entry: Why It Matters
- Milwaukee M12 Fuel Impact Driver: What to Know
- Convert Range of Cells to Numbers in Excel
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Scripting.Dictionary: How It Works and How to Use ItA VBA Scripting.Dictionary stores data as unique keys paired with values, so code can look up an item…
- VBA Filter and Sort in Excel: Code and Key DetailsTo filter and sort a worksheet with VBA, use the AutoFilter method to show matching records and the…
- VBA Loop Through a Dictionary: Keys, Items, and ExamplesTo loop through a VBA Dictionary, use For Each key In dict.Keys, then read each value with dict(key).…
- How to Turn On Excel’s Macro Recorder in Microsoft 365In Excel for Microsoft 365 on Windows, select Developer > Code > Record Macro, set the macro’s name…
- VBA Sort String Array: Methods, Code, and ExamplesVBA has no built-in general-purpose routine for sorting a string array, but you can sort one with a…
- Excel Macro Settings Greyed Out? Causes and How to FixIf Excel macro settings are greyed out, they are usually being controlled by an administrator or you are…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.