View Full Version : Loop Conundrum


hardhat
09-25-2006, 09:01 AM
I have the following VBA code stored as a macro. This loop is designed to remove any lines from the sheet that have "Stock Code" in column A. The routine works but does not remove all the qualifying lines. What happens is that each time it is run it removes half the available qualifying lines until the sheet is clear.

For some background; the data is imported from a legacy reporting tool which includes headers for each page of results. The data is imported into Excel via another macro and by means of fixed width. It is then then sorted retaining the top line of headers. The macro below is used to remove the unwanted header lines.

Any help would be much appreciated.

Sub Remove_Headers()
'start at line 2 to to avoid header'
x = 2
'loop through and remove unwanted lines'
Do While Cells(x, 1).Value > ""
If (Cells(x, 1).Value Like "Stock Code") Then Cells(x, 1).EntireRow.Delete
x = x + 1
Loop
End Sub

boblarson
09-25-2006, 09:18 AM
The problem is that when you delete a row, the row number changes for the following rows, so the one just after the one you deleted is now the same number as the one you deleted. Because of that it bypasses that row.

What you should do is send the start to the last line and then increment your x as x-1 as the row numbers above the point at which you deleted would then not change.

hardhat
09-26-2006, 06:42 AM
Many thanks Bob, it seems so obvious now!