I want to create a for loop to check all of the rows in a sheet that I have and want this code to be able to delete rows if they contain a specified content in certain columns (i.e. if column K contains "June" delete the row. Is there a way to code this?
*Edit I have the code working to search for criteria in one column, but now I need it to search and delete rows based on the data in two columns. i.e. If the data in column K matches cell AJ1 (already have) and the data in column J matches AK1, then delete these rows.
The code I have is this:
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
As a general rule of thumb, you should avoid looping over cells if possible in Excel VBA. Looping over cells is slow and inefficient. It may not matter given the scope of your program, but it is something to be considered. If you are new to VBA programming, it's especially important to pick up good habits early on.
Here is a solution using the
Range.Find
method (MSDN reference) to gather the range of rows to delete, and then delete them all in one statement.This will process rows 2 thru 4000, adjust to suit your needs: