Excel VBA Upper Bound of Array: Quick Guide
In this article
The upper bound of an array in Excel VBA is the highest valid index you can use for that array. You get it with the UBound function. For a fixed-size array declared as Dim scores(1 To 10), UBound(scores) returns 10. For a dynamic array filled by Split, UBound returns the index of the last element. The one-line answer: call UBound(arrayName) for the last index, and UBound(arrayName, dimension) when the array has more than one dimension. This guide shows the exact syntax, how to loop safely from LBound to UBound, and the mistakes that cause run-time error 9 (Subscript out of range).
What You'll Need
- Excel on Windows or Mac with the Visual Basic Editor available (Alt+F11 on Windows; on Mac, use the Developer tab or Tools > Macro > Visual Basic Editor). Menu labels can differ slightly by Excel version and region.
- A workbook saved as .xlsm (macro-enabled) if you want to keep your code.
- Basic familiarity with declaring variables and running a macro.
Step-by-Step
- Open the Visual Basic Editor. In Excel, press Alt+F11 (Windows) or use the Developer tab > Visual Basic (Mac). If the Developer tab is hidden, enable it in Excel Options > Customize Ribbon.
- Insert a module. In the editor, choose Insert > Module. All the code below goes into that module.
- Declare a fixed-size array and read its upper bound. Type this procedure:
Run it with F5. The message box shows 10. Note thatSub FixedArrayDemo() Dim scores(1 To 10) As Integer MsgBox UBound(scores) End SubLBound(scores)returns 1 because the lower bound was declared as 1. If you declareDim scores(10)without1 To, VBA defaults the lower bound to 0, soLBoundis 0 andUBoundis 10 — eleven elements, not ten. - Use UBound on a dynamic array. Declare with empty parentheses, then size it with
ReDimbefore callingUBound:
This returns 5. CallingSub DynamicArrayDemo() Dim names() As String ReDim names(1 To 5) names(1) = "Ada" names(5) = "Grace" MsgBox UBound(names) End SubUBoundon an unallocated dynamic array raises run-time error 9, so alwaysReDimfirst. - Loop from LBound to UBound. This is the standard safe pattern and works whether the array starts at 0 or 1:
Sub LoopDemo() Dim i As Long Dim fruits As Variant fruits = Array("Apple", "Banana", "Cherry") For i = LBound(fruits) To UBound(fruits) Debug.Print i, fruits(i) Next i End SubArray()always returns a zero-based Variant array, so this prints indexes 0, 1 and 2. Press Ctrl+G to see the Immediate window output. - Get the upper bound of one dimension in a 2D array. Pass the dimension number as the second argument: 1 for rows, 2 for columns.
Omitting the dimension argument on a multi-dimensional array returns the upper bound of the first dimension, but stating it explicitly is clearer.Sub TwoDDemo() Dim grid(1 To 3, 1 To 4) As Integer MsgBox UBound(grid, 1) ' returns 3 MsgBox UBound(grid, 2) ' returns 4 End Sub - Handle arrays returned by Split.
Splitreturns a zero-based array, so the last index isUBoundand the count of items isUBound - LBound + 1:
Use the count formula rather than assumingSub SplitDemo() Dim parts As Variant parts = Split("red,green,blue", ",") MsgBox UBound(parts) ' returns 2 MsgBox UBound(parts) - LBound(parts) + 1 ' returns 3 items End SubUBound + 1equals the item count, because that only holds for zero-based arrays. - Guard against empty arrays before reading UBound. If a function might return an uninitialized array, test it first. A common approach is to wrap the call in error handling:
This avoids an unhandled error 9 when the array has not been sized.Sub SafeUBound() Dim data() As Variant On Error Resume Next Dim ub As Long ub = UBound(data) If Err.Number <> 0 Then MsgBox "Array is not initialized" Err.Clear Else MsgBox "Upper bound is " & ub End If On Error GoTo 0 End Sub
Common Mistakes
- Assuming arrays start at 0. A fixed array declared as
Dim a(5)runs from 0 to 5 (six elements). DeclaringDim a(1 To 5)runs from 1 to 5 (five elements). Mixing the two styles in one project causes off-by-one errors. - Using UBound as the element count. For a zero-based array, the count is
UBound - LBound + 1, notUBound. For a one-based array, the count equals UBound only when LBound is 1. - Calling UBound before ReDim. A dynamic array has no bounds until it is sized. This is the most frequent cause of run-time error 9.
- Forgetting the dimension argument on 2D arrays.
UBound(grid)silently returns the first dimension, which may not be what you intended. - Resizing with ReDim without Preserve.
ReDimalone erases existing data. UseReDim Preservewhen you need to keep values, and note that Preserve can only change the last dimension of a multi-dimensional array. - Passing a non-array variable. UBound expects an array. Passing a plain Variant or a Range object raises a type mismatch or error 9.
Tips
- Store
UBoundin a Long variable once before a long loop instead of calling it on every iteration; it is a small speed gain in large loops. - Use
LBoundandUBoundtogether in every loop header so the code survives a change to the array's base index. - When reading a range into a Variant array with
Range.Value, the result is always a 2D array with dimensions (1 To rows, 1 To columns), even for a single column. UseUBound(arr, 1)for the row count. - Prefer
LongoverIntegerfor index variables; VBA converts Integer to Long internally on modern versions anyway. - Add
Option Explicitat the top of the module so undeclared variables are caught at compile time rather than causing confusing run-time errors.
Troubleshooting
- Run-time error 9 (Subscript out of range). The array has not been sized, or you are reading an index outside LBound to UBound. Check that
ReDimruns beforeUBound, and that the array variable is notNothing. - Run-time error 13 (Type mismatch). You passed something that is not an array, such as a single cell value or a Range. Assign the range to a Variant first:
arr = Range("A1:C10").Value. - UBound returns an unexpected number. Check the declaration.
Dim a(10)gives UBound 10 with LBound 0;Dim a(1 To 10)gives UBound 10 with LBound 1. Print bothLBoundandUBoundto confirm. - Data disappears after resizing. You used
ReDimwithoutPreserve. Rebuild the array or restore from a backup; the previous contents are lost. - Macro does not run at all. Check that macros are enabled for the workbook and that the file is saved as .xlsm. Security settings that block macros are found in the Trust Center, and labels vary by version.
Frequently Asked Questions
What does UBound return for an empty array?
An unallocated dynamic array has no bounds, so calling UBound raises run-time error 9. An array sized with ReDim a(0) or ReDim a(0 To 0) has one element and UBound returns 0.
Does UBound work on arrays returned by functions?
Yes, as long as the function returns an array Variant. Assign the result to a Variant variable first, then call UBound on that variable.
How do I get the number of elements rather than the last index?
Use UBound(arr) - LBound(arr) + 1. This works for both zero-based and one-based arrays.
Can I use UBound on a multi-dimensional array without specifying a dimension?
Yes, but it returns the upper bound of the first dimension only. Pass 1 or 2 explicitly to avoid confusion.
Why does UBound of a range-read array start at 1?
When you assign Range.Value to a Variant, VBA creates a 2D array with both dimensions starting at 1. That differs from Array() and Split, which are zero-based.
Is UBound the same on Excel for Mac?
Yes, the VBA language and UBound function behave the same. Only the editor's menu locations and keyboard shortcuts differ.