How to delete multiple rows without a loop in Excel VBA

前端 未结 3 1740
攒了一身酷
攒了一身酷 2020-11-28 15:27

Frequently we are asked how to delete rows based on criteria in one or more columns, and can we use a SpecialCells trick for this?

3条回答
  •  星月不相逢
    2020-11-28 16:19

    Alternatively you can use auto filters:

    Sub clearCells()
    '
    ' Example code for StackOverflow post
    'http://stackoverflow.com/questions/15431801/how-to-delete-multiple-rows-without-a-loop-in-excel-vba
    '
    Dim rngTable As Range
    Dim ws As Worksheet
    Dim StartCell As Range
    
    Const ColumntoFilter1 As Integer = 1
    Const FilterCriteria1 As String = "="
    Const ColumntoFilter2 As Integer = 5
    Const FilterCriteria2 As String = "<>"
    
    Set ws = ActiveSheet
    'Set the starting position (Top-left most position) of your data range
    Set StartCell = ws.Range("A1")
    
    'Turn off autofilter in case it's already active
    ws.AutoFilterMode = False
    'Define data table
    Set rngTable = StartCell.CurrentRegion
    'Filter and delete data
    With rngTable
        .AutoFilter Field:=ColumntoFilter1, Criteria1:=FilterCriteria1
        .AutoFilter Field:=ColumntoFilter2, Criteria1:=FilterCriteria2
        .Offset(1, 0).EntireRow.Delete
    End With
    
    'Turn filters off again
    ws.AutoFilterMode = False
    
    Set rngTable = Nothing
    Set StartCell = Nothing
    Set ws = Nothing
    End Sub
    

提交回复
热议问题