Loop trough some sheets

kamiljaku

New Member
Joined
Jan 5, 2018
Messages
21
Hi,

im trying to paste some values into sheets which names are 1-12. Each of this sheets represents months of the year. Im trying the following macro

Sub wkle()

Dim i As Integer

Dim sh As Worksheet

For i = 1 To 12

ActiveSheet.Range("S46:U52").Copy

Worksheets(i).Activate
Worksheets(i).Range("S46:U52").PasteSpecial

Next i

End Sub







But Excel thinks that i is the number of the sheet and not a name. He pastes the values even if a sheet is called "input".

How to resolve it?
 
Last edited:

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).
You can convert it to a string so that VBA thinks it's a name:

Code:
Sheets(CStr(i)).Activate

There are a few other ways to do this.
 
Last edited:
Upvote 0
Try this.
Code:
Sub wkle()
Dim sh As Worksheet
Dim I As Long

    For I = 1 To 12
    
        ActiveSheet.Range("S46:U52").Copy
        Set sh = Sheets(CStr(I))
        sh.Range("S46:U52").PasteSpecial

    Next I

End Sub
 
Upvote 0
I think this will work, although I just have sheets 1,2,10,11,12 and it shoots an error on sheet 3

How could I possibly make it go to next if one "i" is missing?
 
Upvote 0
Tweaking Norie's code a bit, either of these 2 options would work:

Code:
Sub wkle()
Dim i As Long
    
    ActiveSheet.Range("S46:U52").Copy
    On Error Resume Next
    For i = 1 To 12
        Worksheets(CStr(i)).Range("S46:U52").PasteSpecial
    Next i
End Sub

Code:
Sub wkle()
Dim i As Variant
    
    ActiveSheet.Range("S46:U52").Copy
    For Each i In Array(1, 2, 10, 11, 12)
        Worksheets(CStr(i)).Range("S46:U52").PasteSpecial
    Next i
End Sub

It just depends on whether you have the list of sheets or not.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,940
Messages
6,122,352
Members
449,080
Latest member
Armadillos

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