Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 463
  • Last Modified:

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?
0
ThePATMAN26
Asked:
ThePATMAN26
  • 3
  • 2
2 Solutions
 
Saurabh Singh TeotiaCommented:
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 TeotiaCommented:
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now