Excel VBA Ubound multidimensional array code example

Example 1: excel vba ubound on a multidimensional array

'The VBA UBound() function returns the max index of an array.

MsgBox UBound(vArr)			'<--max index of the first dimension

'There is an optional second argument called rank (that defaults to: 1) 
'that specifies the dimension:

MsgBox UBound(vArr, 2)		'<--max index of the second dimension

'VBA array can have up to 60 dimensions.

'All of the above also applise to the LBound() function.

Example 2: excel vba determine number of elements in a 2D array

'Since VBA arrays can have any integer value for the base element,
'the only sure fire way to determine how many elements is in the array
'is to calculate the value:

MsgBox UBound(Arr) - LBound(Arr) + 1		'<--for elems in 1D array

MsgBox UBound(Arr, 1) - LBound(Arr, 1) + 1	'<--for rows in 2D array
MsgBox UBound(Arr, 2) - LBound(Arr, 2) + 1	'<--for cols in 2D array

Tags:

Vb Example