Basic Loop Not Working - Help!

crmau

New Member
Joined
Oct 29, 2015
Messages
19
Hello,

The following code is not working to loop through each sheet. Basically I want to add one column to every sheet and then copy paste some values from each sheet.

The loop only works on the active sheet and ends up adding three columns, instead of one column to each of my three sheets. Where is the error?

Code:
Sub Formatting()


Dim sht As Worksheet
Dim lRow As Long
    For Each sht In Worksheets
     
            lRow = Cells(Rows.Count, 2).End(xlUp).Row
            Columns("A:A").Insert Shift = xlToRight, _
            CopyOrigin:=xlFormatFromLeftOrAbove
            Range("A5").Value = Range("B1").Value
            Range("A6:A" & lRow).Value = Range("B2").Value
        
    Next sht
End Sub
 

Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
This will loop through each sheet:
Code:
    For Each sht In Worksheets
but doesn't actually select or move to them. So your code continues to procress on the original sheet that was active when kicking off the code.

Try adding this:
Code:
    For Each sht In Worksheets
        [COLOR=#ff0000]sht.Activate[/COLOR]
 
Last edited:
Upvote 0
This will loop through each sheet:
Code:
    For Each sht In Worksheets
but doesn't actually select or move to them. So your code continues to procress on the original sheet that was active when kicking off the code.

Try adding this:
Code:
    For Each sht In Worksheets
        [COLOR=#ff0000]sht.Activate[/COLOR]

Worked like a charm! Thanks!
 
Upvote 0

Forum statistics

Threads
1,224,867
Messages
6,181,479
Members
453,046
Latest member
Excelvbaexpert

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