UBound() returns the highest available subscript of an array dimension; it does not directly return the number of elements. Use it together with LBound() when you need the element count.
Dim myArray(3), i
myArray(0) = "UK"
myArray(1) = "USA"
myArray(2) = "Canada"
myArray(3) = "UAE"
Response.Write "Highest index = " & UBound(myArray)
For i = LBound(myArray) To UBound(myArray)
Response.Write "<br>" & myArray(i)
Next
Here the highest index is 3 and the array contains four elements.
Dim arr(3, 4), totalElements
totalElements = (UBound(arr, 1) - LBound(arr, 1) + 1) * _
(UBound(arr, 2) - LBound(arr, 2) + 1)
Response.Write "Total elements in the array: " & totalElements
Function ArraySize(arr)
ArraySize = UBound(arr) - LBound(arr) + 1
End Function
Dim arr(10)
Response.Write "Size of the array is: " & ArraySize(arr)
Dim arr(5), i, arraySize
For i = LBound(arr) To UBound(arr)
arr(i) = i * 10
Next
arraySize = UBound(arr) - LBound(arr) + 1
Response.Write "Size of array: " & arraySize & "<br>"
For i = LBound(arr) To UBound(arr)
Response.Write "Element " & i & " = " & arr(i) & "<br>"
Next
Dim arr()
ReDim arr(3)
arr(0) = "A"
arr(1) = "B"
arr(2) = "C"
arr(3) = "D"
Response.Write "Size before resizing: " & (UBound(arr) - LBound(arr) + 1) & "<br>"
ReDim Preserve arr(5)
arr(4) = "E"
arr(5) = "F"
Response.Write "Size after resizing: " & (UBound(arr) - LBound(arr) + 1) & "<br>"
For a one-dimensional array the count is UBound(array) - LBound(array) + 1. For multiple dimensions, calculate each dimension separately.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.