VBA数组运行时错误6,溢出

时间:2017-10-25 07:47:09

标签: vba

我有以下功能:

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

我的数组有超过200000个元素,当我尝试打印它时,它会显示下一个错误: Run-time error '6': Overflow

1 个答案:

答案 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即可获得长度。