'Cycle through the tabs and reformat the columns

I have an Excel document consisting of data imported into multiple tabs. The columns in each tab are stretched out and hard to read.

I am trying to cycle through the tabs and reformat the columns.

Sub resize_columns()
'cycles through each tab (have to start in first tab)
'selects all columns and autofits them
 
Dim i As Integer

Dim num As Integer

num = ThisWorkbook.Sheets.Count - 1 'counts number of sheets to use in loop range

For i = 0 To num

    Sheets(ActiveSheet.Index + 1).Activate
    Columns("A:Q").Select
    Columns("A:Q").EntireColumn.AutoFit
    
Next i
    
End Sub

This code produces

"Run-time error '9': Subscript out of range"

The debugger points to the first line inside the For loop.

If I run this code as a test, there is no error:

Sub resize_columns()
'cycles through each tab (have to start in first tab)
'selects all columns and autofits them

Dim i As Integer

For i = 1 To 2

    Sheets(ActiveSheet.Index + 1).Activate
    ActiveSheet.Columns("A:Q").Select
    ActiveSheet.Columns("A:Q").EntireColumn.AutoFit
    
    
Next i
    
End Sub

I have two questions:

1 - How do I loop without the error?
2 - How do I start on the first tab?



Solution 1:[1]

You will rarely need to use Select or Activate with Vba

Sub resize_columns()
   Dim ws As Worksheet
   For Each ws In ThisWorkbook.Sheets
      ws.Columns("A:Q").AutoFit
   Next
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CDP1802