The answer is already posted, you need to delete from the end, rather than from the begining. But why? Lets image you have five columns, and you want to delete columns 2 and 4. Before deleting, this is how your columns look like:
Column index in loop: | 1 | 2 | 3 | 4 | 5 |
Original column number: | 1 | 2 | 3 | 4 | 5 |
Now you start from the begining...
- Index 1: Do nothing (as intended)
- Index 2: Delete (as intended)
Let's pause for a minute. Now let us see how deleting column 2 changed the picture:
Loop direction ---->
Column index in loop: | 1 | 2 | 3 | 4 | 5 |
Original column number: | 1 | 3 | 4 | 5 |
Now you might see that something is wrong. But lets continue the loop for the sake of the example:
- Index 3: Do nothing (but this was originally column 4, and should have been deleted)
- Index 4: Delete (but this was originally column 5, and should NOT have been deleted)
- Index 5: Do nothing (depending on your code, you might get and out of bounds error)
Lets try to go backwards instead, maybe that helps:
- Index 5: Do nothing (as intended)
- Index 4: Delete
Let us pause, once again, to see how it looks now
<---- Loop direction
Column index in loop: | 1 | 2 | 3 | 4 | 5 |
Original column number: | 1 | 2 | 3 | 5 |
Well, something did shift. But as the next step in the loop is 3 (and we are going backwards), it doesn't really matter. Hope that helps the understanding a bit :-)
ForLoop and loop backwards.