Loop macro for all workbooks

VbaHell

Well-known Member
Joined
Jan 30, 2011
Messages
1,220
Hello all

I hope you can help on this please

I want to use this line of code

Cells.EntireColumn.AutoFit

but I would like to run this for all the worksheets in my workbook

I could select each workbook to do this but is there an easy way for the code to loop through all the workbooks please
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Like this:
Code:
    Dim ws As Worksheet
    For Each ws In Worksheets
        ws.Activate
        Cells.EntireColumn.AutoFit
    Next ws
 
Upvote 0
Thanks Joe

One question please if I may

I want run this on all worksheets except "Dashboard"
How could I stop the code from running on "DashBoard" please
 
Upvote 0
Just add an IF block, i.e.
Code:
    Dim ws As Worksheet
    For Each ws In Worksheets
        If ws.Name <> "Dashboard" Then
            ws.Activate
            Cells.EntireColumn.AutoFit
        End If
    Next ws
 
Upvote 0
Try this:
Code:
Sub Auto_Fit()
Dim i As Long
    
    For i = 1 To Sheets.Count
    If Sheets(i).Name <> "Dashboard" Then
        Sheets(i).Cells.Columns.AutoFit
    End If
    Next
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,650
Messages
6,120,734
Members
448,987
Latest member
marion_davis

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