Let's say your Excel sheet contained the following:
A
1 hello
2 moon
3 rich
4 dells
5 cat
The reason your macro wasn't working as desired is because you were successfully creating a new line and then immediately the macro was dropping to the next line and finding the same match, and adding a new empty line, and going to the next line and finding the same match...and on and on.
If we wanted to enter a new line above the line with rich
, a macro like this might work better:
Sub macro1()
Range("A1").Select
' remember the last row that contains a value
Dim LastRow As Integer
Dim CurrentRow As Integer
LastRow = Range("A1").End(xlDown).Row
CurrentRow = 1
' keep on incrementing the current row until we are
' past the last row
Do While CurrentRow <= LastRow
' if the desired string is found, insert a row above
' the current row
' That also means, our last row is going to be one more
' row down
' And that also means, we must double-increment our current
' row
If Range("A" & CurrentRow).Value = "rich" Then
Range("A" & CurrentRow).EntireRow.Insert xlUp
LastRow = LastRow + 1
CurrentRow = CurrentRow + 1
End If
' put the pointer to the next row we want to evaluate
CurrentRow = CurrentRow + 1
Loop
End Sub
After running this, the output will look like this:
A
1 hello
2 moon
3
4 rich
5 dells
6 cat
Give it a try and see how it works for you. Feel free to tweak it for your scenario.