如何在 Excel VBA 中获取数组的长度?
我们使用 UBound 和 LBound 函数来获取 Excel VBA 中数组的长度。在本文中,我们将详细讨论它们。
语法: UBound()函数
UBound (arrayname, [ dimension ])
参数:
- 数组名:必需。数组变量名
- 尺寸:可选
返回:返回数组维度的上限。
语法:LBound()函数
LBound (arrayname, [ dimension ])
参数:
- 数组名:必需。数组变量名
- 尺寸:可选
返回:返回数组维度的下限
样本数据:
VBA代码获取Array(一维数组)的长度:
声明变量:
声明一个大小为 10 的客户数组。
Sub oneDimArrayLength()
' Array variable Declaration
Dim customer (1 To 10) As String
为数组元素赋值
customer(1) = "ANTON"
customer(2) = "BERGS"
customer(3) = "BOLID"
customer(4) = "KOENE"
customer(5) = "FRANS"
使用 UBound函数获取数组的大小并使用消息框显示结果
'Message box to popup length of 1D array
MsgBox "Array has " & UBound(customer) & " element(s)."
End Sub
运行 VBA 代码
按 Alt+F8 弹出宏窗口。选择“ oneDimArrayLength ”并单击R un按钮。
输出
VBA代码获取Array(多维数组)的长度
声明变量:
声明 ProdAndCustomer 多维数组大小为 10 行 2 列
Sub twoDimArrayLength()
' Array variable Declaration
Dim ProdAndCustomer(1 To 10, 1 To 2) As String, noOfRow As Integer, noOfCol As Integer, noOfElements As Integer
为数组元素赋值
ProdAndCustomer(1, 1) = "Alice Mutton"
ProdAndCustomer(2, 1) = "Boston Crab Meat"
ProdAndCustomer(3, 1) = "Camembert Pierrot"
ProdAndCustomer(4, 1) = "Alice Mutton"
ProdAndCustomer(5, 1) = "Ipoh Coffee"
ProdAndCustomer(1, 2) = "ANTON"
ProdAndCustomer(2, 2) = "BERGS"
ProdAndCustomer(3, 2) = "BOLID"
ProdAndCustomer(4, 2) = "BOTTM"
ProdAndCustomer(5, 2) = "FURIB"
使用 UBound 和 LBound函数计算行数、列数。乘以 noOfRow 和 noOfCol 变量得到多维数组中的元素数。
noOfRow = UBound(ProdAndCustomer, 1) - LBound(ProdAndCustomer, 1) + 1
noOfCol = UBound(ProdAndCustomer, 2) - LBound(ProdAndCustomer, 2) + 1
noOfElements = noOfRow * noOfCol
弹出结果的消息框
'Message box to popup length of 1D array
MsgBox "Array has " & noOfElements & " element(s)."
End Sub
运行 VBA 代码
按 Alt+F8 弹出宏窗口。选择“ twoDimArrayLength ”并单击“运行”按钮。
输出: