PDA

View Full Version : How to run macro for multiple worksheets



dax007
01-18-2019, 10:23 AM
Hello,
I have almost 25 different worksheets in one excel file. Now in order to format it I have created a macro for each worksheet. If I go to each worksheet and run the macro for that worksheet it works fine.
Now I'm trying to automate this entire process, run all these macros for the respective worksheet. Can someone please guide or provide me a script that will help me to achieve this task

Any help will be appreciated.

Thank you.

Kenneth Hobs
01-18-2019, 02:10 PM
Welcome to the forum!

I would write the FormatSheet to take an input parameter such as sheet name or sheet object.

If it just acts on the ActiveSheet and say skip sheet named Main, I guess you could do:


Sub Main() Dim wc As Worksheet, ws As Worksheet
Set wc = ActiveSheet
For Each ws In Worksheets
If ws.Name <> "Main" Then
ws.Activate
FormatSheet
End If
Next ws
wc.Activate
End Sub


Sub FormatSheet()
[A1].NumberFormat = "mm/dd/yyyy"
End Sub

nikki333
01-20-2019, 04:50 AM
I would avoid activating each of the sheets like so for example:



Sub Main()
dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Range("A1").NumberFormat = "mm/dd/yyyy"
next ws
End Sub


Or if you want the foratting in a separate sub like so:



Sub Main()
dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
FormatSheets ws
Next ws
End Sub

Sub FormatSheets(ws as Worksheet)
ws.Range("A1").NumberFormat = "mm/dd/yyyy"
End Sub

Paul_Hossler
01-20-2019, 09:35 AM
Hello,
I have almost 25 different worksheets in one excel file. Now in order to format it I have created a macro for each worksheet. If I go to each worksheet and run the macro for that worksheet it works fine.
Now I'm trying to automate this entire process, run all these macros for the respective worksheet. Can someone please guide or provide me a script that will help me to achieve this task

Any help will be appreciated.

Thank you.


Is it the same basic macro for each of the 25 sheets with only the sheet name different, or are there different macros for different sheets?