PDA

View Full Version : Solved: Can't loop through worksheets



starsky
07-21-2009, 07:46 AM
I'm trying to apply some very basic code to all the worksheets in a book, but the macro just won't work. I use an almost idenitical process elsewhere without problem.

It will only apply code to the active ws, and creates too many new columns (I just want 1).

Sub LoopThroughSheets()
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
Columns("C:C").Select
Selection.Insert Shift:=xlToRight
Range("D1:E1").Select
Selection.AutoFill Destination:=Range("C1:E1"), Type:=xlFillDefault
Range("C2").Select
On Error Resume Next

Next ws

End Sub


Any help appreciated.
Thanks

Paul_Hossler
07-21-2009, 08:15 AM
Not tested, but I think you need to qualify the Ranges with ws. like this




ws.Range("C2").Select



Paul

starsky
07-21-2009, 09:13 AM
Finally did it with..

ws.Activate

after the For Each statement.

Thanks.

mdmackillop
07-21-2009, 09:28 AM
Try to avoid Activating and Selecting. Check the Autofill, I may not have the correct cells.

Sub LoopThroughSheets()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Columns("C:C").Insert Shift:=xlToRight
ws.Range("E1:F1").AutoFill Destination:=ws.Range("C1:F1"), Type:=xlFillDefault
Next ws
End Sub

starsky
07-21-2009, 12:32 PM
I see what you mean. Works, thank you.