VBA macros · Formatting

VBA macro to auto-fit all columns on all sheets in Excel

Auto-fit the column widths on every sheet of a workbook at once, with an optional maximum width so long text does not create huge columns.

Windows + Mac

Data pasted from another system usually arrives with columns that are too narrow (showing ####) or far too wide. Double-clicking each column border on every sheet takes ages. This macro auto-fits the used columns of every worksheet in the active workbook and caps very wide columns at a sensible maximum.

VBA
Option Explicit

Sub AutoFitAllColumns()
    Const MAX_WIDTH As Double = 60          ' characters; 0 = no limit
    Dim ws As Worksheet
    Dim col As Range
    Dim skipped As String

    Application.ScreenUpdating = False

    For Each ws In ActiveWorkbook.Worksheets
        If ws.ProtectContents Then
            skipped = skipped & vbLf & ws.Name
        Else
            ws.UsedRange.Columns.AutoFit
            If MAX_WIDTH > 0 Then
                For Each col In ws.UsedRange.Columns
                    If col.ColumnWidth > MAX_WIDTH Then col.ColumnWidth = MAX_WIDTH
                Next col
            End If
        End If
    Next ws

    Application.ScreenUpdating = True

    If Len(skipped) > 0 Then MsgBox "Protected sheets skipped:" & skipped, vbInformation
End Sub
Auto-fit columns on every sheet with a maximum width

How to use it

  1. Open the workbook and press Alt+F11 (Mac: Opt+F11 or Fn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it.
  2. Choose Insert › Module. An empty code window opens on the right.
  3. Paste the whole code into that window. If the module already starts with Option Explicit, do not paste that line twice.
  4. Go back to Excel, press Alt+F8 (Mac: Opt+F8, or Tools › Macro › Macros), pick AutoFitAllColumns and click Run.
  5. Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.

To have this macro ready in every workbook, keep it in your Personal Macro Workbook (PERSONAL.XLSB). If you do not have one yet, record any tiny macro with Store macro in: Personal Macro Workbook (see The macro recorder: record, read and clean up code), then paste this code into a module under VBAProject (PERSONAL.XLSB). The macro works on whichever workbook is active when you run it.

How it works

ws.UsedRange is the rectangle from the first to the last cell that Excel considers in use. Calling .Columns.AutoFit on it fits only those columns, and it measures only the rows of the used range, which is much faster than ws.Cells.EntireColumn.AutoFit on 16,384 columns and a million rows.

Auto-fit makes a column as wide as its longest entry. One long comment can therefore make a column a hundred characters wide. The second loop checks every used column and trims anything wider than MAX_WIDTH. Column width is measured in characters of the default font, so 60 is roughly sixty digits. Set the constant to 0 to switch the cap off.

Protected sheets refuse format changes, so the macro skips them and lists them at the end rather than stopping with an error. Screen updating is off while it runs, which matters in workbooks with many sheets; see Make your macros fast: speed optimization in VBA.

Change it

Variations people often need:

  • Rows too: add ws.UsedRange.Rows.AutoFit after the column line. This is useful after turning on Wrap Text.
  • Only the active sheet: replace the loop with ActiveSheet.UsedRange.Columns.AutoFit.
  • Fit to the header row only, ignoring long values below it: ws.UsedRange.Rows(1).Columns.AutoFit. Calling AutoFit on a single row's cells sizes the columns to that row.
  • A minimum width as well, so empty columns do not shrink to nothing: add If col.ColumnWidth < 8 Then col.ColumnWidth = 8 inside the inner loop.

Auto-fit is often combined with a tidy start view; run VBA macro to set all sheets to 100% zoom and select A1 afterwards to finish the job before sending the file.

What can go wrong

Merged cells are ignored by auto-fit, so a title merged across A1:F1 does not widen column A. That is usually what you want. Cells with Wrap Text switched on do not make a column wider; they make the row taller instead.

Watch out. If the used range is much larger than your real data (for example because someone formatted entire columns), auto-fit takes longer and may fit empty columns to their minimum width. Clean the sheet with VBA macro to reset the used range and clear excess formatting first.

Numbers that still show #### after auto-fitting are usually dates or numbers with a format wider than the maximum width, or negative dates. Raise MAX_WIDTH or check the values.

Tip. Works the same on Windows and Mac. Column widths depend on the default font, so a file can look slightly different on a computer with different fonts.

Related: VBA macro to set all sheets to 100% zoom and select A1, VBA macro to reset the used range and clear excess formatting.

More vba macros