我想创建一个for循环来检查我所拥有的工作表中的所有行,并希望此代码能够删除行,如果它们在某些列中包含指定的内容(即,如果列K包含“June”)删除行。有没有办法对此进行编码?
*编辑 我有代码在一列中搜索条件,但现在我需要它来根据两列中的数据搜索和删除行。即,如果列K中的数据与单元格AJ1(已经有)匹配,并且列J中的数据与AK1匹配,则删除这些行。
我的代码是:
Sub DeleteRows()
Sheets("Sheet1").Select
Dim rFind As Range
Dim rDelete As Range
Dim strSearch As String
Dim iLookAt As Long
Dim bMatchCase As Boolean
strSearch = Range("AJ1")
iLookAt = xlWhole
bMatchCase = False
Set rDelete = Nothing
Application.ScreenUpdating = False
With Sheet1.Columns("K:K")
Set rFind = .Find(strSearch, LookIn:=xlValues, LookAt:=iLookAt, SearchDirection:=xlPrevious, MatchCase:=bMatchCase)
If Not rFind Is Nothing Then
Do
Set rDelete = rFind
Set rFind = .FindPrevious(rFind)
If rFind.Address = rDelete.Address Then Set rFind = Nothing
rDelete.EntireRow.Delete
Loop While Not rFind Is Nothing
End If
End With
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:2)
作为一般经验法则,如果可能,应避免在Excel VBA中循环遍历单元格。循环遍历单元格为slow and inefficient。考虑到你的程序范围,这可能无关紧要,但这是需要考虑的事情。如果您不熟悉VBA编程,那么在早期养成良好习惯尤为重要。
这是一个使用Range.Find
方法(MSDN reference)来收集要删除的行范围的解决方案,然后在一个语句中将它们全部删除。
Sub DeleteRows()
Dim rngResults As Range, rngToDelete As Range
Dim strFirstAddress As String
With Worksheets("Sheet1").UsedRange 'Adjust to your particular worksheet
Set rngResults = .Cells.Find(What:="June") 'Adjust what you want it to find
If Not rngResults Is Nothing Then
Set rngToDelete = rngResults
strFirstAddress = rngResults.Address
Set rngResults = .FindNext(After:=rngResults)
Do Until rngResults.Address = strFirstAddress
Set rngToDelete = Application.Union(rngToDelete, rngResults)
Set rngResults = .FindNext(After:=rngResults)
Loop
End If
End With
If Not rngToDelete Is Nothing Then rngToDelete.EntireRow.Delete
Set rngResults = Nothing
End Sub
答案 1 :(得分:0)
这将处理行 2 至 4000,进行调整以满足您的需求:
Sub RowKiller()
Dim K As Range, rKill As Range
Set K = Range("K2:K4000")
Set rKill = Nothing
For Each r In K
v = r.Text
If InStr(1, v, "June") > 0 Then
If rKill Is Nothing Then
Set rKill = r
Else
Set rKill = Union(r, rKill)
End If
End If
Next r
If Not rKill Is Nothing Then
rKill.EntireRow.Delete
End If
End Sub