Most efficient way to delete row with VBA

前端 未结 4 377
粉色の甜心
粉色の甜心 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:50

    In this case a simple working formula can be used to see if each of the values in your range to be tested (column A of schedule) exist in column F of misc

    In B4 it would =MATCH(A4,misc!D:D,0)

    This can be used manually or with code for an efficient delete as the formula by design returns an error if there is no match which we can efficiently delete with VBA with either:

    • AutoFilter
    • SpecialCells (the design piece*)

    In xl2007 note that there is a limit of 8192 discrete areas that can be selected with SpecialCells

    code

    Sub ReCut()
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim rng1 As Range
    
    Set ws1 = Sheets("misc")
    Set ws2 = Sheets("schedule")
    
    With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .DisplayAlerts = False
    End With
    
    Set rng1 = ws2.Range(ws2.[a4], ws2.Cells(Rows.Count, "A").End(xlUp))
    ws2.Columns(2).Insert
    With rng1.Offset(0, 1)
         .FormulaR1C1 = "=MATCH(RC[-1],'" & ws1.Name & "'!C[2],0)"
         On Error Resume Next
        .Cells.SpecialCells(xlCellTypeFormulas, xlErrors).EntireRow.Delete
         On Error GoTo 0
    End With
    
    ws2.Columns(2).Delete
    
    With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .DisplayAlerts = True
    End With
    End Sub
    

提交回复
热议问题