位置:首页 » 文章/教程分享 » VBA UBound函数

UBound 函数返回指定数组的最大下标。因此,这个值对应于该数组的大小。

语法 :

UBound(ArrayName[,dimension])
  1. ArrayName, 必需的参数。该参数对应于所述数组的名称。

  2. dimension, 一个可选的参数。此情况对应于所述阵列的维数的整数值。如果它是“1”,则它返回下界第一维; 如果是“2”,则它返回下界第二维,依此类推。

示例 :

添加一个按钮,并添加以下功能

Private Sub Constant_demo_Click()
  Dim arr(5) as Variant
  arr(0) = "1"           'Number as String
  arr(1) = "VBScript     'String
  arr(2) = 100 		     'Number
  arr(3) = 2.45 		     'Decimal Number
  arr(4) = #10/07/2013#  'Date
  arr(5) = #12.45 PM#    'Time
  msgbox("The smallest Subscript value of  the given array is : " & UBound(arr))

  ' For MultiDimension Arrays :
  Dim arr2(3,2) as Variant
  msgbox("The smallest Subscript of the first dimension of arr2 is : " & UBound(arr2,1))
  msgbox("The smallest Subscript of the Second dimension of arr2 is : " & UBound(arr2,2))
  
End Sub

当执行函数输出如下所示:

The Largest Subscript value of the given array is : 5
The Largest Subscript of the first dimension of arr2 is : 3
The Largest Subscript of the Second dimension of arr2 is : 2