Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Upper Bound of Array: Quick Guide

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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.
  2. Insert a module. In the editor, choose Insert > Module. All the code below goes into that module.
  3. Declare a fixed-size array and read its upper bound. Type this procedure:
    Sub FixedArrayDemo()
        Dim scores(1 To 10) As Integer
        MsgBox UBound(scores)
    End Sub
    Run it with F5. The message box shows 10. Note that LBound(scores) returns 1 because the lower bound was declared as 1. If you declare Dim scores(10) without 1 To, VBA defaults the lower bound to 0, so LBound is 0 and UBound is 10 — eleven elements, not ten.
  4. Use UBound on a dynamic array. Declare with empty parentheses, then size it with ReDim before calling UBound:
    Sub DynamicArrayDemo()
        Dim names() As String
        ReDim names(1 To 5)
        names(1) = "Ada"
        names(5) = "Grace"
        MsgBox UBound(names)
    End Sub
    This returns 5. Calling UBound on an unallocated dynamic array raises run-time error 9, so always ReDim first.
  5. 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 Sub
    Array() always returns a zero-based Variant array, so this prints indexes 0, 1 and 2. Press Ctrl+G to see the Immediate window output.
  6. 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.
    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
    Omitting the dimension argument on a multi-dimensional array returns the upper bound of the first dimension, but stating it explicitly is clearer.
  7. Handle arrays returned by Split. Split returns a zero-based array, so the last index is UBound and the count of items is UBound - LBound + 1:
    Sub 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 Sub
    Use the count formula rather than assuming UBound + 1 equals the item count, because that only holds for zero-based arrays.
  8. 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:
    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
    This avoids an unhandled error 9 when the array has not been sized.

Common Mistakes

  • Assuming arrays start at 0. A fixed array declared as Dim a(5) runs from 0 to 5 (six elements). Declaring Dim 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, not UBound. 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. ReDim alone erases existing data. Use ReDim Preserve when 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 UBound in 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 LBound and UBound together 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. Use UBound(arr, 1) for the row count.
  • Prefer Long over Integer for index variables; VBA converts Integer to Long internally on modern versions anyway.
  • Add Option Explicit at 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 ReDim runs before UBound, and that the array variable is not Nothing.
  • 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 both LBound and UBound to confirm.
  • Data disappears after resizing. You used ReDim without Preserve. 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.