如何在vba上的一个条件下自动删除完整的行?

时间:2017-09-14 11:35:45

标签: excel vba excel-vba loops

我是Vba的初学者。我有以下简单的循环代码,以便从数据库中删除具有" na"的行。第9列单元格的值:

Dim n As Integer
n = 500

  For i = 1 To n
  If Cells(i, 9).Value = "n.a." Then
    Rows("i:i").Select
    Selection.Delete Shift:=xlUp

   End If
  Next i

End Sub

但我收到1004错误,有人可以帮我吗?

非常感谢

3 个答案:

答案 0 :(得分:3)

Option Explicit

Public Sub TestMe()

    Dim n As Integer
    n = 500

    For i = n To 1 Step -1
        If Cells(i, 9).value = "n.a." Then
            rows(i & ":" & i).Select
            Selection.Delete Shift:=xlUp
        End If
    Next i

End Sub

无论何时删除行,都要从最大到最小的行开始。稍后您可以谷歌如何避免Select以及如何使用Union以便一步完成删除。最后,您可以将Integer替换为Long

答案 1 :(得分:3)

你只需要这个......

Dim n As Integer
n = 500
  For i = n To 1 Step -1
    If Cells(i, 9).Value = "n.a." Then Rows(i).Delete
  Next i

修改

或者更准确地说这是为了让它变得动态......

Application.ScreenUpdating = False
Dim n As Long
n = Cells(Rows.Count, 9).End(xlUp).Row
  For i = n To 1 Step -1
    If Cells(i, 9).Value = "n.a." Then Rows(i).Delete
  Next i
Application.ScreenUpdating = True

答案 2 :(得分:1)

删除这些值的最快方法是使用AutoFilters。不需要循环。

Option Explicit

Public Sub AutoFilterDelete()

  With Range("I1:I500")
    .AutoFilter Field:=1, Criteria1:="n.a"
    .Resize(WorksheetFunction.Match("*", .Cells, -1)).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    .Parent.AutoFilterMode = False
  End With

End Sub