Excel VBA - Find a row containing a keyword and other rows in relation to the find.

I need to search every row in a document for a set keyword. On the instances it is found I need the code to return the row # and then select the row before the instance, the row containing the instance, and the two rows after it so they can all be deleted. What is the easiest way of accomplishing this?
ThePATMAN26Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Saurabh Singh TeotiaConnect With a Mentor Commented:
Assuming you are searching A Column, You can use the following cod which will start from row-1 and will go to the last used row of A Column..
Saurabh...

Sub delete()
    Application.ScreenUpdating = False
 
    Dim i As Long
    i = 1
    Do Until i > Cells(65536, "a").End(xlUp).Row
        If Cells(i, "a").Value = "Your keyword here which you are searching for" Then
            Rows(i - 1 & ":" & i + 2).delete
        Else
            i = i + 1
        End If
    Loop
 
    MsgBox "Done"
 
 
    Application.ScreenUpdating = True
 
End Sub

Open in new window

0
 
ThePATMAN26Author Commented:
Saurabh,

That works perfectly - but I need to revise my question a little bit. The document I am searching has a varying number of spaces before the instances of the word I am looking for. As I don't know the combination of the number of spaces plus the keyword it doesn't always work. How would I write the code if I needed to account for different characters and spaces at the beginning of the word "apple' (for example.)
0
 
Saurabh Singh TeotiaConnect With a Mentor Commented:
You can change the line-7 and add a trim to it, to trim the additional spaces you have in your data...like this...
If trim(Cells(i, "a").Value) = "Your keyword here which you are searching for" Then
Or alternaitvely you can use this If statement as well..

If instr(trim(Cells(i, "a").Value) , "Your keyword here which you are searching for")>0 Then  
Both the statements will do what you are looking for..
Saurabh...
0
 
ThePATMAN26Author Commented:
One more question actually - I now want to sub the keyword with a string variable but can't seem to make it happen.
0
 
ThePATMAN26Author Commented:
nevermind my last comment - figured it out. Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.