Why is this locking up? Loop through all rows, perform function on duplicate, delete duplicate row

后端 未结 3 1655
旧巷少年郎
旧巷少年郎 2021-01-27 07:33

The code works when I bite off a couple hundred rows at a time, but always hangs somewhere in the middle when I try to run it on 10,000.

What the code does:

3条回答
  •  醉话见心
    2021-01-27 08:11

    Start with this and let us know how things are going afterwards:

    Option Explicit
    
    Sub combineDelete()
    
    Const TEST_COLUMN As String = "A"
    Dim i As Long
    Dim iLastRow As Long
    Dim s As Double, t As Double, u As Double
    Dim v As Double, w As Double, y As Double
    
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .EnableEvents = False
    End With
    
    With ActiveSheet
        iLastRow = .Cells(.Rows.Count, TEST_COLUMN).End(xlUp).Row
        For i = iLastRow To 2 Step -1
            If .Cells(i, 1).Value2 = .Cells(i - 1, 1).Value2 Then
                s = .Cells(i, 3).Value2
                t = .Cells(i - 1, 3).Value2
                .Cells(i - 1, 3).Value2 = s + t
                u = .Cells(i, 4).Value2
                v = .Cells(i - 1, 4).Value2
                .Cells(i - 1, 4).Value2 = u + v
                w = .Cells(i, 5).Value2
                y = .Cells(i - 1, 5).Value2
                .Cells(i - 1, 5).Value2 = w + y
                .Rows(i).EntireRow.Delete
            End If
        Next i
    End With
    
    With Application
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With
    
    End Sub
    

    Notes:

    1. Disable screenupdating, calculations and events
    2. Use .Value2 instead of .Value
    3. Explicit coding
    4. Missing references to ActiveSheet added by adding dots .
    5. Dim all variables to avoid variants

提交回复
热议问题