VBA 索引函数大小限制

标签 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.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

但是,由于 Index 函数,更改数组大小会导致类型不匹配错误。
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 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

关于VBA 索引函数大小限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23788597/

相关文章:

Java Apache POI Excel读取异常

vba - 在 VBA 中交替行打印

vba - 在打开的单元格中显示 Excel 帐户用户名

database - 从一个字段可能有多个值的数据库中查询

ms-access - MS Access 在长时间不活动后断开与 ODBC 表的连接

.net - 如何将WPF应用程序制作为可以嵌入MS Excel中的OLE对象?

excel - VBA:使用变量传递列数组时删除重复项失败

c# - 日期时间到 Excel 区域问题

excel - Code Golf : Numeric equivalent of an Excel column name

excel - 如何在不使用其他软件的情况下将 SSIS 导出到 Microsoft Excel?