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

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
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,214,830
Messages
6,121,839
Members
449,051
Latest member
excelquestion515

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