Link to home
Start Free TrialLog in
Avatar of growedup
growedup

asked on

Can you go backwards in a For Each Loop?

Let's say I'm going through cells in a range.

For Each cell in sheet.Range(myRange)

Open in new window


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

Open in new window


Thanks.
Avatar of Ingeborg Hawighorst (Microsoft MVP / EE MVE)
Ingeborg Hawighorst (Microsoft MVP / EE MVE)
Flag of New Zealand image

Hello,

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
For Each cell in sheet.Range(myRange)
    If deleteRow then 
         cell.offset(-1, 0).EntireRow.Delete
    End If
Next

Open in new window

Avatar of growedup
growedup

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
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.
That didn't work.  It still started at A1.
ASKER CERTIFIED SOLUTION
Avatar of RobSampson
RobSampson
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial