Compare two sheets using arrays

前端 未结 1 519
你的背包
你的背包 2021-01-03 04:19

My code is super slow (10+ min for each sheet) due to the quantity of data i have. I believe there may be a way to speed it up using arrays, but i am not sure how to go abo

1条回答
  •  心在旅途
    2021-01-03 04:35

    Welcome to SO. Great question. Give this procedure a shot. You could probably tidy it up a bit, but it should work and be significantly faster.

    For reference, see this link.

    Update: I tested this on two randomly generated data sets of 10K and 11K rows. It took less than a blink of an eye. I didn't even have time to look at see the time when I started.

    Option Explicit
    
    Private Sub cmdCompare2to1_Click()
    
    Dim sheet1 As Worksheet, sheet2 As Worksheet, sheet3 As Worksheet
    Dim lngLastR As Long, lngCnt As Long
    Dim var1 As Variant, var2 As Variant, x
    Dim rng1 As Range, rng2 As Range
    
    
    Set sheet1 = Worksheets(1)
    Set sheet2 = Worksheets(2)
    Set sheet3 = Worksheets(3) ' assumes sheet3 is a blank sheet in your workbook
    
    Application.ScreenUpdating = False
    
    'let's get everything all set up
    'sheet3 column headers
    sheet3.Range("A1:B1").Value = Array("in1Not2", "in2Not1")
    
    'sheet1 range and fill array
    With sheet1
    
        lngLastR = .Range("A" & .Rows.Count).End(xlUp).Row
    
        Set rng1 = .Range("A1:A" & lngLastR)
        var1 = rng1
    
    End With
    
    'sheet2 range and fill array
    With sheet2
    
        lngLastR = .Range("A" & .Rows.Count).End(xlUp).Row
    
        Set rng2 = .Range("A1:A" & lngLastR)
        var2 = rng2
    
    End With
    
    'first check sheet1 against sheet2
    On Error GoTo NoMatch1
    For lngCnt = 1 To UBound(var1)
    
        x = Application.WorksheetFunction.Match(var1(lngCnt, 1), rng2, False)
    
    Next
    
    
    'now check sheet2 against sheet1
    On Error GoTo NoMatch2
    For lngCnt = 1 To UBound(var2)
    
        x = Application.WorksheetFunction.Match(var2(lngCnt, 1), rng1, False)
    
    Next
    
    On Error GoTo 0
    Application.ScreenUpdating = True
    Exit Sub
    
    NoMatch1:
        sheet3.Range("A" & sheet3.Rows.Count).End(xlUp).Offset(1) = var1(lngCnt, 1)
        Resume Next
    
    
    NoMatch2:
        sheet3.Range("B" & sheet3.Rows.Count).End(xlUp).Offset(1) = var2(lngCnt, 1)
        Resume Next
    
    
    End Sub
    

    0 讨论(0)
提交回复
热议问题