Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting via autofilter takes too long

Tags:

excel

vba

I have roughly 8000+ rows. Using autofilter to delete rows takes a few minutes. I thought autofilter was the defacto FAST way to delete (instead of looping row by row). How can I speed it up? Is there a faster way? To be fair, half of the rows are deleted XD

With ThisWorkbook.Worksheets("Upload")
    lastRow = .Cells(.Rows.Count, "S").End(xlUp).Row
    Set dataRng = .Range(.Cells(4, 1), .Cells(lastRow, 19))
    dataRng.AutoFilter field:=19, Criteria1:="=0"
    Application.DisplayAlerts = False
    dataRng.Offset(1, 0).Resize(dataRng.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Rows.Delete
    Application.DisplayAlerts = True
    .ShowAllData
End With
like image 443
findwindow Avatar asked Dec 01 '15 19:12

findwindow


Video Answer


1 Answers

I'll challange to underlying assumption that AutoFilter is the fast way to go - it is often hard to beat a loop over a variant array

This demo shows a way to do this, on my system processing 8000+ rows removing half runs in sub-second

Sub DEMO()
    Dim datrng As Range
    Dim dat, newdat
    Dim i As Long, j As Long, k As Long
    With ThisWorkbook.Worksheets("Upload")
        Set datrng = .Range(.Cells(1, 1), .Cells(.Rows.Count, "S").End(xlUp))
    End With
    dat = datrng.Value
    ReDim newdat(1 To UBound(dat, 1), 1 To UBound(dat, 2))
    j = 1
    For i = 1 To UBound(dat, 1)
        If dat(i, 19) <> 0 Then ' test for items you want to keep
            For k = 1 To UBound(dat, 2)
                newdat(j, k) = dat(i, k)
            Next
            j = j + 1
        End If
    Next

    datrng = newdat
End Sub
like image 143
chris neilsen Avatar answered Oct 06 '22 22:10

chris neilsen