嵌套for循环的替代方法,可加快运行时间

时间:2019-11-06 21:58:58

标签: vba performance loops

我有一个嵌套的for循环,该循环首先运行10-15k行,将该行中的单元格与另一个40k +行的表进行比较,如果找到匹配项,则返回该匹配项,否则将写入“ no record”在一个单元格中。该代码运行良好,只是研究了一种替代方法以使其运行更快。目前,运行13000条线大约需要50分钟到一个小时。我已经研究了数组,但是加载包含40k +个项目的数组似乎是错误的方法。该报告通常一次运行一次,因此,当第一次创建该报告时,它可能有2k行,然后可能会向其中添加3k行,下面的代码将跳过已经检查过的行,并从停下来的地方提取。任何帮助表示赞赏

For i = 2 To lastRow
    If Cells(i, 83).Value <> "" Then GoTo NextIteration:
    Sheets("mft Rpt").Cells(i, 83) = "No Record"
    model = Sheets("MFT RPT").Cells(i, 11).Value
    trimModel = Replace(Replace(model, " ", ""), "-", "")
    For j = 1 To lastCollateralRow
        If trimModel = Sheets("Promosheet Table").Cells(j, 1).Value Then
            Sheets("MFT RPT").Cells(i, 83) = Sheets("promosheet Table").Cells(j, 3).Value
        End If
    Next j
NextIteration:
Next i

2 个答案:

答案 0 :(得分:0)

这仅仅是一个概念证明,您将需要调整变量和范围以适合您的需求。

Sub ProofOfConcept()

    Dim rngList As Range
    Dim rngMatch As Range

    Dim arrList As Variant
    Dim arrMatch As Variant

    Set rngList = Range("A1:A50000")
    arrList = Application.Transpose(rngList.Value)

    Set rngMatch = Range("C1:D15000")
    arrMatch = Application.Transpose(rngMatch.Value)

    For a = 1 To 15000
        For b = 1 To 50000
            If arrMatch(1, a) = arrList(b) Then
                arrMatch(2, a) = "Match found"
                GoTo skip
            End If
        Next
skip:
    Next

    rngMatch = WorksheetFunction.Transpose(arrMatch)




End Sub

答案 1 :(得分:0)

感谢@Michal

玩了一下。我使用这段代码将运行时间从一个小时缩短到了大约7或8分钟。效果很好!

Dim promoList As Range
Dim rngMatch As Range
Dim arrList As Variant
Dim arrMatch As Variant
Dim z


Set promoList = Sheets("promosheet table").Range("A1:A" & lastcollateralRow)
arrList = Application.Transpose(promoList.Value)
Set rngMatch = Sheets("Mft rpt").Range("K2:K" & lastRow)
arrMatch = Application.Transpose(rngMatch.Value)
For z = LBound(arrMatch) To UBound(arrMatch)
    arrMatch(z) = Replace(Replace(arrMatch(z), " ", ""), "-", "")
Next

For A = 1 To lastRow
    If Cells(A + 1, 83).Value <> "" Then GoTo skip:
    Sheets("mft rpt").Cells(A + 1, 83) = "No Record"
    For b = 1 To lastcollateralRow + 1
        If arrMatch(A) = promoList(b) Then
            Sheets("mft rpt").Cells(A + 1, 83) = promoList(b, 3)
            GoTo skip
        End If
    Next
skip:
Next