excel/VBA如何将数组的可变长度赋值给整型变量

excel/VBA how to assign the variable length of an array to integer variable

在 excel/VBA 我有这个代码

Dim colName as Variant
Dim lengthToDispl as Integer
colName = Array("A", "B", "C")
lengthToDispl = colName.length

我收到以下错误 'Object Required'。它与最后一行有关。

如何将可变长度数组(包含字符串)的长度分配给变量(整数)?

你想要 return 数组的 'size' 的函数是 UBound function which returns the Upper Boundary. This is often used with its counterpart, the LBound function 其中 return 是 下边界 .

这可能是也可能不是 return您要查找的号码。一些数组使用从零开始的索引排列,而有些数组使用从一开始的索引。这取决于它们的声明和分配方式。

colName = Array("A", "B", "C")

上面创建了一个数组,索引从零开始,三个元素位于 colName(0)colName(1)colName(2) 位置。 UBound(例如 UBound(colName))将 return 2,而不是 3。要循环使用它,请同时使用 LBound 和 UBound。

for i = LBound(colName) to UBound(colName)
    debug.print colName(i)
next i

从工作表的单元格中分配值时,您会得到一个基于一的二维数组,即使您只是从单个列或行中收集值也是如此。另一个维度或 Rank 只是 1 到 1.

colName = Range("A1:C2").Value2

这将创建一个二维数组,索引从一开始,如 ReDim colName (1 to 2, 1 to 3)

debug.print LBound(colName, 1) & " to " & UBound(colName, 1)
debug.print LBound(colName, 2) & " to " & UBound(colName, 2)

for i = LBound(colName, 1) to UBound(colName, 1)
    for j = LBound(colName, 2) to UBound(colName, 2)
        debug.print colName(i, j)
    next j
next i

我建议在处理数组元素时同时使用 LBound and UBound