Most efficient way to delete row with VBA

前端 未结 4 434
粉色の甜心
粉色の甜心 2021-01-14 12:27

I currently have a macro that I use to delete a record if the ID doesn\'t exist in a list of ID\'s I created from an XML document. It does work like I want it to, however I

4条回答
  •  情书的邮戳
    2021-01-14 12:48

    This code uses AutoFilter and is significantly faster than looping through rows.

    I use it daily and it should be pretty easy to figure out.

    Just pass it what you're looking for and the column to search in.

    You could also hard-code the column if you want.

    private sub PurgeRandy
        Call FindDelete("F", "Randy")
    end sub
    

    Public Sub FindDelete(sCOL As String, vSearch As Variant) 'Simple find and Delete
    Dim lLastRow As Integer
    Dim rng As Range
    Dim rngDelete As Range
        Range(sCOL & 1).Select
        [2:2].Insert
        [2:2] = "***"
        Range(sCOL & ":" & sCOL).Select
    
        With ActiveSheet
            .UsedRange
                lLastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
            Set rng = Range(sCOL & 2, Cells(lLastRow, sCOL))
                rng.AutoFilter Field:=1, Criteria1:=vSearch
            Set rngDelete = rng.SpecialCells(xlCellTypeVisible)
                rng.AutoFilter
                rngDelete.EntireRow.Delete
            .UsedRange
        End With
    End Sub
    

提交回复
热议问题