vba - 使用 Excel 宏 VBA 在 excel 范围内查找行的最快方法

标签 vba excel

我有一个 Excel 电子表格(sheet2),记录数约为 100 万。我正在迭代这些记录,并且对于每次迭代,我将一行选定的列与 sheet1 中大约 2000 条记录的另一个范围进行比较。

rangeA = 1 Million rows 'Sheet2
rangeB = 2000 rows 'Sheet1

With sheet1
For Each row In rangeA.Columns.Rows

   For Each rangeBRow In rangeB.Columns.Rows
     If (.Cells(rangeBRow.Row,1).Value = CName And .Cells(rangeBRow.Row,2).Value = LBL ... ) Then
     ' Do something cool... set some cell value in sheet2
     Exit For
     End If
   Next rangeBRow

Next row
End With

我对上述代码的问题是它需要很长时间才能完成执行。除了为 2000 行迭代一百万条记录之外,还有其他最快和快速的方法来针对 excel 宏中的一系列行查找一行吗?

感谢您的时间。

最佳答案

12 秒检查 5k 行和 200k 行:

Sub Compare()

    Dim rngA As Range, rngB As Range
    Dim dict As Object, rw As Range
    Dim a As Application, tmp As String

    Set a = Application
    Set dict = CreateObject("scripting.dictionary")

    Set rngA = Sheet1.Range("A2:F200000")
    Set rngB = Sheet1.Range("K2:P5000")

    For Each rw In rngA.Rows
        'Create a key from the entire row and map to row
        ' If your rows are not unique you'll have to do a bit more work here
        ' and use an array for the key value(s)
        dict.Add Join(a.Transpose(a.Transpose(rw.Value)), Chr(0)), rw.Row
    Next rw

    For Each rw In rngB.Rows
        'does this row match one in range A?
        tmp = Join(a.Transpose(a.Transpose(rw.Value)), Chr(0))
        If dict.exists(tmp) Then
            rw.Cells(1).Offset(0, -1).Value = dict(tmp)
        End If
    Next rw

End Sub

关于vba - 使用 Excel 宏 VBA 在 excel 范围内查找行的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22685622/

相关文章:

regex - vba:正则表达式,从公式字符串中删除除单元格引用行引用之外的所有引用

sql - 当列名是数字时,使用 VB.NET 中的 ADO 查询 Excel

arrays - 如何返回数组中的多个值 - Excel VBA

vba - 如何检测 vba 中的合并单元格(Word 2010)

Excel VBA,Http.ResponseText 运行时错误 91

Excel 2007 数字没有小数但不自动舍入?

c# - 如何在 ExcelInterop 中查找第一个和最后一个单元格以及 C# 中的图形范围

java - 使用 Java 和 Apache poi 从 .xls 或 .xlsx 文件中读取内容

excel - 我怎样才能让我的超链接工作? (Excel,VBA)

vba - 通过本地 VBA 浏览 https SharePoint 文件和文件夹