相反的循環和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