根据设置条件删除多行

时间:2018-12-27 20:14:31

标签: excel vba

Sub Macro()
Dim i As Long
For i = Cells(Rows.Count, 14).End(xlUp).Row To 2 Step -1
    If Cells(i, 14).Value2 = "APPLE" Then
        Rows(i).Delete
    End If
Next i

Dim f As Long
For f = Cells(Rows.Count, 14).End(xlUp).Row To 2 Step -1
    If Cells(f, 14).Value2 = "NAME" Then
        Rows(f).Delete
    End If
Next f
End Sub

我有上面提到的代码,删除了上面有苹果和名字的所有行,如果可能的话,我希望excel在一行或两行中执行代码。您的帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

Dim i As Long
For i = Cells(Rows.Count, 14).End(xlUp).Row To 2 Step -1
    IF Cells(i, 14).Value2 = "APPLE" OR Cells(i, 14).Value2 = "NAME" THEN Rows(i).Delete
Next i

答案 1 :(得分:1)

删除行的快速方法是使用“自动筛选”:

Sub FastDelete()
    Dim rng As Range, rngVisible As Range
    '//Remove filter if any
    ActiveSheet.AutoFilterMode = False
    '// Get range of only one column (N)
    Set rng = Range(Cells(1, 14), Cells(Rows.Count, 14).End(xlUp))
    '// Field:=1 because filter has only one field
    rng.AutoFilter Field:=1, Criteria1:=Array("APPLE", "NAME"), Operator:=xlFilterValues
    '// Have error handling in case if no data is found
    On Error Resume Next
    With rng
        '// Use Offset and Resize to exclude header
        Set rngVisible = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
    End With
    '// If rows were found (i.e. there's no error), delete them
    If Err = 0 Then rngVisible.EntireRow.Delete
    On Error GoTo 0
    '// Remove filter
    ActiveSheet.AutoFilterMode = False
End Sub