VBA索引函数大小限制

VBA索引函数大小限制,vba,excel,Vba,Excel,在单元格A1:A66000中,我有数字1,2。。。66000 Sub addData() Application.ScreenUpdating = False Cells(1, 1) = 1 Cells(2, 1).Formula = "=A1+1" Range(Range("A66000"), Range("A66000").End(xlUp)).Select Selection.FillDown Application.ScreenUpdati

在单元格A1:A66000中,我有数字1,2。。。66000

Sub addData()
    Application.ScreenUpdating = False
    Cells(1, 1) = 1
    Cells(2, 1).Formula = "=A1+1"
    Range(Range("A66000"), Range("A66000").End(xlUp)).Select
    Selection.FillDown
    Application.ScreenUpdating = True
End Sub
下面的代码将数据加载到数组中,并查找数字2的索引。它返回正确的结果2

Sub test()
    Dim arr As Variant
    arr = ArrayFromRange(Range("A1:A65536"))
    MsgBox Application.WorksheetFunction.Match(2, Application.Index(arr, 0, 1), 0)
End Sub
但是,由于索引函数,更改数组大小会导致类型不匹配错误

Sub test()
    Dim arr As Variant
    arr = ArrayFromRange(Range("A1:A65537"))
    MsgBox Application.WorksheetFunction.Match(2, Application.Index(arr, 0, 1), 0)
End Sub
我怎样才能避开这件事?我正在使用Excel2007

编辑:我忘了包括我正在调用的这个方便的函数

Function ArrayFromRange(rg As Range) As Variant()
'==============================================================================================
'Returns an array from a given range
'                                                                                   BG Feb 2013
'==============================================================================================

    If (rg.Cells.Count = 1) Then
        Dim arr(1 To 1, 1 To 1) As Variant
        arr(1, 1) = rg.Value
        ArrayFromRange = arr
    Else
        ArrayFromRange = rg ' Arr is now an allocated array
    End If
End Function

由于您可以在VBA中传递到WorksheetFunction.xxxx的数组的大小有一个硬限制,因此您可以将数据保留在工作表上,并直接查询它。这样做的优点是速度更快

Sub test()
    Dim arr As Variant, v, t, i As Long
    Dim rng As Range

    Set rng = ActiveSheet.Range("A1:A65536")

    arr = rng.Value

    'array-based approach
    t = Timer
    For i = 1 To 100
        v = Application.WorksheetFunction.Match(i, Application.Index(arr, 0, 1), 0)
        If i <= 5 Then Debug.Print v
    Next i
    Debug.Print Timer - t '>> 1.55 sec

    'query worksheet directly
    t = Timer
    For i = 1 To 100
        v = rng.Parent.Evaluate("MATCH(" & i & ", INDEX(" & rng.Address() & ", 0, 1), 0)")
        If i < 5 Then Debug.Print v
    Next i
    Debug.Print Timer - t  '>> 0.008 sec

End Sub
子测试()
尺寸arr为变型,v、t、i为长型
变暗rng As范围
设置rng=ActiveSheet.Range(“A1:A65536”)
arr=平均值
“基于阵列的方法
t=计时器
对于i=1到100
v=Application.WorksheetFunction.Match(i,Application.Index(arr,0,1),0)
如果我在这里讨论: