In VBA, the Len function does not return the length of an array; it returns the number of bytes in a string or variable. To get the length (number of elements) of an array, you use UBound and LBound together: UBound(arr) - LBound(arr) + 1. This gives the total element count for a one-dimensional array; for multi-dimensional arrays, you must apply it per dimension.
Why Len Doesn’t Work on Arrays
The Len function in VBA is designed for strings and simple data types. When you pass an array to Len, VBA throws a Type Mismatch error (Error 13) because an array is not a scalar value. This is a common misconception because in other languages like JavaScript or Python, len() works on arrays and strings alike. In VBA, the language separates the concept of string length (bytes) from array size (element count).
For example, Len("Hello") returns 5 (the number of characters, each 1 byte). But Len(Array(1,2,3)) will error. The correct approach is to use the array’s own bounds.
How to Get the Length of a 1D Array
For a one-dimensional array, the length (element count) is calculated as:
Dim arr(1 To 5) As Integer
Dim lenArr As Long
lenArr = UBound(arr) - LBound(arr) + 1
' lenArr = 5
If the array is zero-based (declared as Dim arr(0 To 4) or implicitly as Dim arr(5) which gives indices 0 to 5), the formula still works: UBound(arr) - LBound(arr) + 1. For Dim arr(5), LBound is 0, UBound is 5, so length = 6.
Always include LBound because VBA arrays can have any lower bound, especially when declared with Option Base 1 or when receiving arrays from other sources.
Multi-Dimensional Arrays: Length per Dimension
For a two-dimensional array, there is no single “length”—you need the count of rows and columns separately. Use UBound(arr, 1) and UBound(arr, 2) for the upper bounds, and similarly for lower bounds.
Dim matrix(1 To 3, 1 To 4) As Double
Dim rows As Long, cols As Long
rows = UBound(matrix, 1) - LBound(matrix, 1) + 1 ' = 3
cols = UBound(matrix, 2) - LBound(matrix, 2) + 1 ' = 4
For three or more dimensions, repeat for each dimension index. There is no built-in function to get the total number of elements across all dimensions; you must multiply the counts.
Using Array Length in Loops
The most common use of array length is in For loops. Instead of hardcoding bounds, always use LBound and UBound to avoid errors when the array is empty or has non-standard bounds.
Dim arr() As Variant
arr = Array("a", "b", "c")
Dim i As Long
For i = LBound(arr) To UBound(arr)
Debug.Print arr(i)
Next i
This works even if the array is empty (UBound < LBound), though you should check for emptiness first.
Checking if an Array is Empty
An array can be declared but not yet sized, such as Dim arr() As Variant. To check if it has been allocated, use IsArray and then check bounds. A common pattern:
If IsArray(arr) Then
If UBound(arr) < LBound(arr) Then
MsgBox "Array is empty"
Else
MsgBox "Array has " & UBound(arr) - LBound(arr) + 1 & " elements"
End If
Else
MsgBox "Not an array"
End If
Note that UBound on an unallocated array raises an error, so always check with IsArray first.
Common Errors and Pitfalls
One frequent mistake is using Len(arr) and getting a Type Mismatch error. Another is assuming arrays are always zero-based. If you use Option Base 1 at the top of a module, all implicit arrays start at 1, so UBound(arr) alone would give the length, but relying on that is fragile. Always use UBound - LBound + 1.
Another pitfall: when you use the Array function, the returned array is always zero-based, regardless of Option Base. So Array("a","b") has LBound 0 and UBound 1, length 2.
When passing arrays to procedures, they are passed by reference by default. Inside the procedure, UBound works fine, but if you try to ReDim the parameter, you must declare it as ByRef or ByVal appropriately.
Alternatives: WorksheetFunction.CountA and Other Methods
If you have an array that came from a range, you might be tempted to use WorksheetFunction.CountA to count non-empty cells, but that returns the number of non-empty values, not the array length. For a range, the array returned by Range.Value is always a 2D array (even for a single column), so you need to use UBound(arr, 1) for rows.
For dynamic arrays, you can also use the Len of a joined string as a hack, but that is unreliable and not recommended. Stick with UBound and LBound.
Performance and Best Practices
Calling UBound and LBound is extremely fast, so there is no performance concern. However, avoid calling them repeatedly inside a loop if the array bounds do not change. Store the bounds in variables before the loop.
Dim arr(1 To 1000) As Long
Dim i As Long, lb As Long, ub As Long
lb = LBound(arr)
ub = UBound(arr)
For i = lb To ub
' do something
Next i
This is a best practice for readability and minor speed gains.
Frequently Asked Questions
Can I use Len on an array to get its length?
No. Len is for strings and simple data types. For arrays, use UBound(arr) - LBound(arr) + 1.
How do I get the number of elements in a 2D array?
Get the length of each dimension separately: rows = UBound(arr, 1) - LBound(arr, 1) + 1, columns = UBound(arr, 2) - LBound(arr, 2) + 1. Multiply them if you need the total.
What does UBound return for an empty array?
If the array is declared but not sized, calling UBound raises a Subscript Out of Range error. Check with IsArray and compare bounds to avoid errors.
Is there a built-in VBA function like LEN for arrays?
No. VBA does not have a single function for array length. The standard practice is to use UBound and LBound.
Does Option Base 1 affect the length calculation?
Yes, it changes the default lower bound for arrays declared without explicit bounds. But the formula UBound - LBound + 1 still works correctly because it uses the actual bounds.
Can I use LenB on an array?
No. LenB is for byte counts in strings. Arrays are not supported.
Related
- Google Sheets VLOOKUP: How to Use It Correctly
- Google Finance Dividend Yield: How to Find It
- Snowflake to Number: Convert with TO_NUMBER & CAST
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA: Hide a Column by Number in Your WorksheetTo hide a column by its number in Excel VBA, set that worksheet column’s Hidden property to True.…
- Excel VBA Like Statement: Patterns and ExamplesIn Excel VBA, the Like operator compares a string with a pattern and returns whether the string matches…
- How to Set a Macro in ExcelIn Excel for Microsoft 365 on Windows, set a macro by opening a workbook, choosing Developer > Record…
- Copy-Paste VBA Code: Add, Run, and Troubleshoot ItTo copy and paste VBA code into Excel for Microsoft 365 on Windows, press Alt+F11 to open the…
- PowerPoint VBA InputBox Location and How to Position ItIn PowerPoint VBA, call the built-in InputBox function from a macro; its optional XPos and YPos arguments set…
- VBA Code to Disable Copy and Paste in ExcelTo block the usual copy-and-paste keyboard shortcuts in Excel for Microsoft 365 on Windows, use VBA’s Application.OnKey method…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.