for loop missing out columns

BigDelGooner

Board Regular
Joined
Aug 17, 2009
Messages
197
I have the following for..loop that is missing out columns because when the Columns(c.Column).Delete is executed it automatically moves to the 'next c' and then when the code loops its passes another 'next c' command.

For Each c In Range(Cells(1, 3), Cells(1, Range("IV1").End(xlToLeft).Column))
If c.Value = 0 Then
Columns(c.Column).Delete
End If
Next c

How do I get round this? Is there a 'Previous c' kind of command that I could put in after the Columns(c.Column).Delete command?
 

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN
Try looping backwards:

Code:
Dim lngCol As Long, lngLastCol As Long
lngLastCol = Cells(1, Columns.Count).End(xlToLeft).Column
 
For lngCol = lngLastCol To 3 Step -1
    If Cells(1, lngCol).Value = 0 Then
        Columns(lngCol).Delete
    End If
Next lng
 
Last edited:
Upvote 0
When deleting rows or columns you should loop backwards through them:

Code:
Dim lastCol As Long, myCol As Long
lastCol = Cells(1, "IV1").End(xlToLeft).Column
For myCol = lastCol To 3 Step -1
    If Cells(1, myCol) = 0 Then Columns(myCol).Delete
Next myCol
Next c

Dom
 
Upvote 0

Forum statistics

Threads
1,215,067
Messages
6,122,949
Members
449,095
Latest member
nmaske

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top