Fastest way to delete rows which cannot be grabbed with SpecialCells

后端 未结 3 532
深忆病人
深忆病人 2020-11-28 14:49

Based on another question on this site I started wondering about the fastest way to delete all rows with a certain condition.

The above-referenced question came with

3条回答
  •  悲哀的现实
    2020-11-28 15:36

    edited

    after some more testings it seems that Sort&Delete is a little faster than RemoveDuplicates

    so I put in the following solution (keeping the first one for reference by the end of the answer)

    Sub FixWithSort()
    Dim testRng As Range
    Dim dttStart As Date
    
    Set testRng = Worksheets("Test").Range("I25:I50000")
    
    With testRng
        .Formula = "=RandBetween(1, 5)"
        .Value2 = .Value2
    End With
    
    dttStart = Now()
    
    With testRng
        With .Offset(, 1)
            .FormulaR1C1 = "=IF(RC[-1]=2,"""",row())"
            .Value2 = .Value2
        End With
    
        .Resize(, 2).Sort key1:=.Columns(2), Orientation:=xlTopToBottom, Header:=xlYes
        Range(.Cells(1, 2).End(xlDown).Offset(1, -1), .Cells(1, 1).End(xlDown)).EntireRow.Delete
        .Columns(2).ClearContents
    End With
    
    Debug.Print Format(Now() - dttStart, "HH:MM:SS")
    dttStartGlobal = dttStartGlobal + Now() - dttStart
    
    End Sub
    

    previous (and a little slower) solution with RemoveDuplicates

    Option Explicit
    
    Sub FixWithRemoveDuplicates()
    Dim testRng As Range
    Dim dttStart As Date
    
    Set testRng = Worksheets("Test").Range("I25:I50000")
    
    With testRng
        .Formula = "=RandBetween(1, 5)"
        .Value2 = .Value2
    End With
    
    dttStart = Now()
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    
    With testRng
        With .Offset(, 1)
            .FormulaR1C1 = "=IF(RC[-1]=2,""a"",row())"
            .Value2 = .Value2
        End With
        .EntireRow.RemoveDuplicates Columns:=Array(.Columns(2).Column), Header:=xlNo
        .Offset(, 1).Find(what:="a", LookIn:=xlValues, LookAt:=xlWhole).EntireRow.Delete
        .Columns(2).ClearContents
    End With
    
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    
    Debug.Print Format(Now() - dttStart, "HH:MM:SS")
    'Average time around 0 seconds
    
    End Sub
    

提交回复
热议问题