Excel VBA: How to Get the Size of an Array
In this article
Getting the size of an array in Excel VBA is straightforward, but it requires understanding how VBA handles bounds. Unlike some languages that offer a simple `.Length` property for all array types, VBA relies on functions like `UBound` and `LBound` to determine the upper and lower limits of an array's indices. The "size" or total number of elements is calculated by subtracting the lower bound from the upper bound and adding one. This guide explains exactly how to retrieve these values for both static and dynamic arrays.
What You'll Need
- A workbook with macros enabled (.xlsm format).
- Access to the Visual Basic Editor (VBE) via Alt + F11.
- Basic knowledge of declaring variables in VBA.
Step-by-Step
- Open the Visual Basic Editor: Press
Alt + F11in Excel to open the VBE. If you do not see your project, ensure the Project Explorer window is visible by pressingCtrl + R. - Insert a Module: Right-click on any folder in the Project Explorer, select
Insert, and then chooseModule. This creates a blank code window where you can write your subroutine. - Declare Your Array: Inside your new module, start writing a Sub procedure. For example, type
Sub CheckArraySize(). Declare an array variable. You can use a static array likeDim myArray(5) As Stringor a dynamic array likeDim dynArray() As Integer. - Populate the Dynamic Array (If Applicable): If you are using a dynamic array, you must resize it before checking its size. Use the
ReDimstatement, such asReDim dynArray(0 To 9). Note that without this step, the array has no defined bounds, and attempting to check them will cause an error. - Calculate the Upper Bound: Use the
UBoundfunction to find the highest index number in the array. Assign this to a variable, for example:upperLimit = UBound(myArray). - Calculate the Lower Bound: Use the
LBoundfunction to find the lowest index number. By default, VBA arrays start at 0 unless specified otherwise (or ifOption Base 1is set). Assign this value:lowerLimit = LBound(myArray). - Determine the Total Size: Calculate the total number of elements using the formula:
totalElements = upperLimit - lowerLimit + 1. This accounts for inclusive indexing. - Output the Result: Use a message box to display the result for verification. Type
MsgBox "Array Size: " & totalElements. Run the macro by pressingF5while the cursor is inside the sub.
Common Mistakes
One frequent error is assuming that UBound returns the total count of elements. It does not; it returns the index of the last element. For a zero-based array with 10 items, UBound returns 9, not 10. Always remember to add 1 to the difference between bounds.
Another common issue involves uninitialized dynamic arrays. If you declare Dim arr() As Variant but never use ReDim to assign it a size, calling UBound(arr) will trigger a runtime error (Error 9: Subscript out of range). You must initialize the array dimensions before querying its size.
Developers often forget about the Option Base setting. While modern VBA defaults to 0, legacy code might have Option Base 1 at the top of a module. In this case, LBound will return 1 instead of 0. Using LBound explicitly rather than hardcoding 0 prevents bugs when switching between modules with different base settings.
Tips
For multi-dimensional arrays, specify the dimension number in the UBound and LBound functions. For example, UBound(myMatrix, 1) gets the upper bound of the first dimension (rows), while UBound(myMatrix, 2) gets the second dimension (columns). Omitting the dimension argument defaults to the first dimension.
If you frequently need to check if an array is empty, create a helper function. An array is considered empty if it has not been redimensioned or if its upper bound is less than its lower bound (which can happen in specific edge cases or after certain operations). A robust check looks like this: IsEmptyArray = (Not IsArray(arr)) Or (UBound(arr) < LBound(arr)).
Use IsArray() before attempting to get bounds if the variable might be passed as a generic Variant. This prevents type mismatch errors if the variable holds a single value instead of an array.
Troubleshooting
Error 9: Subscript out of range: This almost always means you are trying to access an array that hasn't been initialized. Check if you used ReDim for dynamic arrays. Ensure the index you are testing against actually exists within the bounds.
Unexpected Size Values: If the size seems off by one, verify whether your array is zero-based or one-based. Print LBound and UBound separately to diagnose. Remember that a static declaration like Dim x(5) creates 6 elements (indices 0 through 5), whereas Dim x(1 To 5) creates 5 elements.
Code Not Running: Ensure your file is saved as a Macro-Enabled Workbook (.xlsm). If security settings block macros, the code will not execute. Go to File > Options > Trust Center > Trust Center Settings > Macro Settings and enable macros for trusted locations.
Frequently Asked Questions
Does VBA have a .Length property for arrays?
No, standard VBA arrays do not have a .Length property. You must calculate the length using UBound - LBound + 1. However, collections and dictionaries do have a .Count property.
How do I get the size of a two-dimensional array?
You calculate the size of each dimension separately. For rows, use UBound(arr, 1) - LBound(arr, 1) + 1. For columns, use UBound(arr, 2) - LBound(arr, 2) + 1. Multiply these two results to get the total number of cells in the matrix.
Can I change the size of an array after creating it?
Yes, but only if it is declared as a dynamic array (using parentheses without numbers, e.g., Dim arr()). You use the ReDim statement to resize it. Adding the Preserve keyword (ReDim Preserve arr(newSize)) keeps existing data intact, though you can only change the last dimension.
What happens if I call UBound on an empty dynamic array?
It raises a runtime error because the array has no defined boundaries. You should check if the array has been allocated memory using ReDim or handle the error with On Error Resume Next followed by a check of the Err object.
Is Option Base 1 recommended for new projects?
Generally, no. Most developers prefer the default Option Base 0 because it aligns with most other programming languages and Excel's internal indexing for ranges and controls. Explicitly defining bounds (e.g., Dim arr(1 To 10)) is clearer than relying on global module settings.