Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to AutoFit Excel Columns With or Without VBA

Fit a column to its contents with a double-click, or add a worksheet macro that resizes selected columns when you click their headers.

Table of Contents

In Excel, double-click the right edge of a column’s header to fit its width to the contents. To resize several columns, select their headers first and double-click a boundary in the selection. Use VBA only if you want the width to adjust whenever you select an entire column on a specific worksheet.

AutoFit without a macro

Select the columns, then use Home > Format > AutoFit Column Width. For rows, choose AutoFit Row Height. Very long text can make a column wider than you want. Set a fixed width and use Wrap Text in that case. See ways to adjust column width and row height.

AutoFit when you select a column header

  1. In desktop Excel, right-click the worksheet tab and choose View Code. The code belongs in that sheet’s module.

    How to adjust auto width on Excel Picture 1

  2. Use the Worksheet and SelectionChange dropdowns to locate the event. If Excel created a procedure already, put the conditional lines inside it. A sheet can have only one procedure with that event name.

    How to adjust auto width on Excel Picture 2

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Rows.Count = Me.Rows.Count Then
        Target.EntireColumn.AutoFit
    End If
End Sub

How to adjust auto width on Excel Picture 3

Save as an .xlsm workbook. With macros allowed for this trusted workbook, select a different cell, then click a column header to test. Clicking a single cell does not resize the column. The screenshot shows the AutoFit line. The condition above limits it to full-column selections.

How to adjust auto width on Excel Picture 4

VBA does not run in Excel for the web. To remove the behavior, delete the event procedure you added or just the lines you inserted into an existing one. See Microsoft’s guide to the SelectionChange event and other ways to resize and manage Excel cells.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.