VBA索引函数大小限制

在单元格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 

以下代码将数据加载到数组中,并find数字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 

但是,更改数组大小会导致由于索引函数而导致的“types不匹配”错误。

 Sub test() Dim arr As Variant arr = ArrayFromRange(Range("A1:A65537")) MsgBox Application.WorksheetFunction.Match(2, Application.Index(arr, 0, 1), 0) End Sub 

我怎样才能解决这个问题? 我正在使用Excel 2007。

编辑:我忘了包括这个方便的function,我打电话

 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