How to AutoFit Columns Using VBA (With Example)


You can use the AutoFit method in VBA to autofit the width of one or more columns in an Excel spreadsheet.

Here is one common way to use this method in practice:

Sub AutoFitColumns()
Columns("A:D").AutoFit
End Sub

This particular macro automatically adjusts the width of each column in the range from A to D to be as wide as necessary to display the longest cell in each column.

The following example shows how to use the AutoFit method in practice.

Example: How to AutoFit Columns Using VBA

Suppose we have the following dataset in Excel that contains information about various basketball players:

Suppose we would like to automatically adjust the width of each column from A to D to be as wide as necessary to display the longest cell in each column.

We can create the following macro to do so:

Sub AutoFitColumns()
Columns("A:D").AutoFit
End Sub

When we run this macro, we receive the following output:

Notice that the width of each column has been automatically adjusted to be as wide as necessary to display the longest cell in each column.

Note that if you would like to autofit every column in a specific worksheet, you can use the following syntax instead:

Sub AutoFitColumns()
ThisWorkbook.Worksheets("Sheet1").Cells.EntireColumn.AutoFit
End Sub

This particular macro will autofit the width of every column in Sheet1 to be as wide as necessary to display the longest cell in each column.

Note: You can find the complete documentation for the AutoFit method in VBA .

x