joselyn reda
joselyn reda

Reputation: 17

Autofit columns starting with a specific worksheet

below is the formula I want to use. I'm just not sure how to add the command to start from a specific worksheet.

Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
sh.Columns.AutoFit
Next sh
End Sub

Upvotes: 1

Views: 50

Answers (1)

braX
braX

Reputation: 11755

Sure, use an Index instead:

Dim nIndex As Integer
For nIndex = 1 To ThisWorkbook.WorkSheets.Count
  ThisWorkbook.WorkSheets(nIndex).Columns.AutoFit
Next 

Change the 1 to whichever one you want to start with.

Or you could check the name of the worksheet in the loop instead, and process all of them after and including that one:

Dim bFlag As Boolean ' default value is False
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
  If sh.Name = "First One" Then bFlag = True
  ' once the flag is set to True, it stays True til the end
  If bFlag Then sh.Columns.AutoFit
Next

Upvotes: 1

Related Questions