VBA Loop Worksheets not working

Joey_Ng

New Member
Joined
Mar 7, 2020
Messages
25
Office Version
  1. 365
Platform
  1. Windows
Hi,

I am trying to loop through each worksheet in a workbook but the code only works for the activesheet and not looping through the other sheets. I tried both below codes but neither works.

Sub test()
Dim ws As Worksheet
For Each ws In Sheets
Range("A1") = "test"
Next ws
End Sub

OR

Sub test2()
Dim i As Integer
For i = 2 To Worksheets.Count
Range("A1") = "test"
Next i
End Sub

Any idea what the issue is? The code works fine for the activesheet but it won't move to the next sheet so it repeats the actions for the activesheet.


Many Thanks,

Joseph
 

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.
you need to qualify the Range to the ws object variable

Rich (BB code):
Sub test()
    Dim ws As Worksheet
    For Each ws In Worksheets
        ws.Range("A1") = "test"
    Next ws
End Sub

Dave
 
Upvote 0
Thanks Dave. That works.

Revised code below also works.
Sub test2()
Dim i As Integer
For i = 2 To Worksheets.Count
Sheets(i).Range("A1") = "test"
Next i
End Sub

Much appreciated.
 
Upvote 0
Rich (BB code):
Sub test2()
Dim i As Integer
For i = 2 To Worksheets.Count
Worksheets(i).Range("A1") = "test"
Next i
End Sub

Advisable to refer to Worksheets in your code as Sheets will refer to both worksheet & chart sheets

Dave
 
Upvote 0

Forum statistics

Threads
1,214,893
Messages
6,122,121
Members
449,066
Latest member
Andyg666

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