我已经接近找出正确的方法来做到这一点,但我都被搜查了。我正在尝试搜索包含各种垃圾的列(资产标签),但希望保留以AA开头的整个行,因为这确认该行实际上是资产标记。
下面的代码给了我一个“Object Required”错误,我相信我可能没有正确地告诉它用“如果rng.Cells(i)<> Left(cell.Value, 2)=“AA”然后“声明。有人能指出我需要做的正确方向吗?
Sub DeleteRows()
Dim rng As Range
Dim i As Double, counter As Double
Set rng = Range("C:C")
i = 1
For counter = 1 To rng.Rows.count
If rng.Cells(i) <> Left(cell.Value, 2) = "AA" Then
rng.Cells(i).EntireRow.Delete
Else
i = i + 1
End If
Next
End Sub
谢谢!
答案 0 :(得分:3)
如果要删除行,则应始终自下而上:
Sub DeleteRows()
Dim rng As Range
Dim counter As Long, numRows as long
With ActiveSheet
Set rng = Application.Intersect(.UsedRange, .Range("C:C"))
End With
numRows = rng.Rows.Count
For counter = numRows to 1 Step -1
If Not rng.Cells(counter) Like "AA*" Then
rng.Cells(counter).EntireRow.Delete
End If
Next
End Sub
答案 1 :(得分:0)
鉴于您的代码耗时5分钟,我建议您尝试使用此AutoFilter方法。它使用工作列(使用范围的第一个未使用的列部分)来运行C列单元格的前两个字母为“AA”的区分大小写的文本。如果不是,则自动过滤器会删除这些行。
Sub KillnonAA()
Dim ws As Worksheet
Dim rng1 As Range
Dim lRow As Long
Dim lCol As Long
Set ws = ActiveSheet
'in case the sheet is blank
On Error Resume Next
lRow = ws.Cells.Find("*", , xlValues, , xlByRows, xlPrevious).Row
lCol = ws.Cells.Find("*", , xlValues, , xlByColumns, xlPrevious).Column
On Error GoTo 0
If lRow = 0 Then Exit Sub
Set rng1 = ws.Range(ws.Cells(1, lCol + 1), ws.Cells(lRow, lCol + 1))
Application.ScreenUpdating = False
Rows(1).Insert
With rng1.Offset(0, 1)
.FormulaR1C1 = "=EXACT(LEFT(RC3,2),""AA"")"
.AutoFilter Field:=1, Criteria1:="FALSE"
.EntireRow.Delete
'in case all records were deleted
On Error Resume Next
.EntireColumn.Delete
On Error GoTo 0
End With
Application.ScreenUpdating = True
End Sub