VBA – Autofit Columns

After you manipulate a worksheet with VBA it may be necessary to Autofit your columns to present the nicest end result possible. Here’s how to autofit columns using VBA.

Autofit Column using VBA

This code autofits columns A and B. The autofit is applied to the active sheet.

Columns("A:B").EntireColumn.Autofit

Autofit All Used Columns

What if you want to Autofit all of the used columns in a worksheet? Use the above method in combination with Count the Number of Used Columns, and a loop.

The following code autofits all used columns using VBA:


Sub AutofitAllUsed()

Dim x As Integer

For x = 1 To ActiveSheet.UsedRange.Columns.Count

     Columns(x).EntireColumn.autofit

Next x

End Sub