我是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错误,有人可以帮我吗?
非常感谢
答案 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