相反的循环和1个参考各小区1,抓住一切,把它变成一个变种阵列;然后循环变体数组。
入门:
Sub Sample()
' Look in Column D, starting at row 2
DeleteRowsWithValue "@", 4, 2
End Sub
真正的工人:
Sub DeleteRowsWithValue(Value As String, Column As Long, StartingRow As Long, Optional Sheet)
Dim i As Long, LastRow As Long
Dim vData() As Variant
Dim DeleteAddress As String
' Sheet is a Variant, so we test if it was passed or not.
If IsMissing(Sheet) Then Set Sheet = ActiveSheet
' Get the last row
LastRow = Sheet.Cells(Sheet.Rows.Count, Column).End(xlUp).Row
' Make sure that there is work to be done
If LastRow < StartingRow Then Exit Sub
' The Key to speeding up the function is only reading the cells once
' and dumping the values to a variant array, vData
vData = Sheet.Cells(StartingRow, Column) _
.Resize(LastRow - StartingRow + 1, 1).Value
' vData will look like vData(1 to nRows, 1 to 1)
For i = LBound(vData) To UBound(vData)
' Find the value inside of the cell
If InStr(vData(i, 1), Value) > 0 Then
' Adding the StartingRow so that everything lines up properly
DeleteAddress = DeleteAddress & ",A" & (StartingRow + i - 1)
End If
Next
If DeleteAddress <> vbNullString Then
' remove the first ","
DeleteAddress = Mid(DeleteAddress, 2)
' Delete all the Rows
Sheet.Range(DeleteAddress).EntireRow.Delete
End If
End Sub
首先,限制了细胞的数量来遍历。即,而不是'范围(E:E)',使用其中包含数据的范围 – shahkalpesh
我一直想知道如何做到这一点 - 如何选择包含第一个单元格的范围,直到包含数据的最后一个单元格? – Parseltongue
http://www.rondebruin.nl/win/s4/win001.htm - 看看这个。我相信,它会为你回答。回想你的问题,假设你在包含数据的单元格A1中,现在按Ctrl +向下箭头。这将选择所有从A1开始的单元格,直到包含数据的最后一个单元格为止(注意:中间不应该有空单元格)。使用VBA,你可以'lastCell = Range(“A1”)。End(xlDown)' – shahkalpesh