我有以下功能:
Function ArrayLength(arr() As Double) As Integer
Dim len As Integer
Dim i As Integer
len = UBound(arr) - LBound(arr)
ArrayLength = len
End Function
'Print on console array
Sub PrintArray(arr() As Double, column As Integer)
Dim len As Integer
len = ArrayLength(arr)
For i = 0 To len - 1
ActiveSheet.Cells(i + 2, column).Value = arr(i)
Next i
End Sub
答案 0 :(得分:0)
除此之外,你应该使用long
而不是integer
,你的数组长度公式有点不对。它少了一个。看看这段代码:
Function ArrayLength(arr) As Long
Dim k As Long
Dim i As Long
k = UBound(arr) - LBound(arr)
ArrayLength = k
End Function
Public Sub TestMe()
Dim arr() As Variant
arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
Debug.Print ArrayLength(arr)
End Sub
它将返回8,而答案应为9.为了获得长度,只需写Debug.Print UBound(arr) + 1
即可获得长度。