vba 获取数组的长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30574814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get length of array?
提问by lisovaccaro
I'm trying to get the length of an array, yet I keep getting this error:
我正在尝试获取数组的长度,但我不断收到此错误:
Object required
所需对象
Am I doing something wrong?
难道我做错了什么?
Dim columns As Variant
columns = Array( _
"A", "ID", _
"D", "Name")
Debug.Print columns.Length ' Error: Object required
回答by AnalystCave.com
Length of an array:
数组长度:
UBound(columns)-LBound(columns)+1
UBound(columns)-LBound(columns)+1
UBoundalone is not the best method for getting the length of every array as arrays in VBA can start at different indexes, e.g Dim arr(2 to 10)
UBound单独不是获取每个数组长度的最佳方法,因为 VBA 中的数组可以从不同的索引开始,例如 Dim arr(2 to 10)
UBoundwill return correct results only if the array is 1-based (starts indexing at 1 e.g. Dim arr(1 to 10). It will return wrong results in any other circumstance e.g. Dim arr(10)
UBound只有当数组是基于 1 的时候才会返回正确的结果(例如从 1 开始索引Dim arr(1 to 10)。它会在任何其他情况下返回错误的结果,例如Dim arr(10)
More on the VBA Arrayin this VBA Array tutorial.
更多关于VBA数组在此VBA阵列教程。
回答by MarredCheese
Function
功能
Public Function ArrayLen(arr As Variant) As Integer
ArrayLen = UBound(arr) - LBound(arr) + 1
End Function
Usage
用法
Dim arr(1 To 3) As String ' Array starting at 1 instead of 0: nightmare fuel
Debug.Print ArrayLen(arr) ' Prints 3. Everything's going to be ok.
回答by Pavlos Fragkiadoulakis
If the variant is empty then an error will be thrown. The bullet-proof code is the following:
如果变体为空,则会引发错误。防弹代码如下:
Public Function GetLength(a As Variant) As Integer
If IsEmpty(a) Then
GetLength = 0
Else
GetLength = UBound(a) - LBound(a) + 1
End If
End Function
回答by meMadhav
Try CountA:
尝试CountA:
Dim myArray(1 to 10) as String
Dim arrayCount as String
arrayCount = Application.CountA(myArray)
Debug.Print arrayCount

