growedup
asked on
Can you go backwards in a For Each Loop?
Let's say I'm going through cells in a range.
Can I go backwards if a statement is true? In other words, return to the previous cell.
Thanks.
For Each cell in sheet.Range(myRange)
Can I go backwards if a statement is true? In other words, return to the previous cell.
For Each cell in sheet.Range(myRange)
If deleteRow then
<go back a cell>
cell.EntireRow.Delete
End If
Next
Thanks.
ASKER
Ah, I should clarify. I intend to to do more with the row after I the previous one.
The project is basically sorting a list. I want all the cells in the column that contain (not equal to) a certain word at the top. My code goes through each cell, if the word is not in the cell then I move it to the bottom. I also apply some formatting.
I tried your solution before I asked my question and the problem is that when a row is deleted, it skips some rows because all the row numbers change. If I am on row 4 and I delete row 3, row 4 now becomes row 3 but cell still equals row 4.
Simplistically put, I am doing this:
go through each cell in column
if deleteRow then delete the row above, set deleteRow to false
does the cell contain the keyword?
if yes, apply formatting.
if no, move to bottom of list, apply formating, set deleteRow to True
start over
The project is basically sorting a list. I want all the cells in the column that contain (not equal to) a certain word at the top. My code goes through each cell, if the word is not in the cell then I move it to the bottom. I also apply some formatting.
I tried your solution before I asked my question and the problem is that when a row is deleted, it skips some rows because all the row numbers change. If I am on row 4 and I delete row 3, row 4 now becomes row 3 but cell still equals row 4.
Simplistically put, I am doing this:
go through each cell in column
if deleteRow then delete the row above, set deleteRow to false
does the cell contain the keyword?
if yes, apply formatting.
if no, move to bottom of list, apply formating, set deleteRow to True
start over
ASKER
I just reread your post. So can I go backwards in a range? (A25:A1)? That seems like it would fix my problem. I will try.
ASKER
That didn't work. It still started at A1.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I was afraid of that. Not a big deal, I suppose. I just have to change my code a bit. I was hoping there was a way to do it using For Each... Thanks for the help.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
you can, but for deleting rows it is better to start at the bottom and work upwards. What are you trying to achieve?
Here is your code amended.
Better alternatives can be provided if you explain your project.
cheers, teylyn
Open in new window