Excel Macro – Autofit width and height

|

AutoFit() is designed to run in your Personal.xlsb with a keyboard function of Ctrl+d to select all columns and rows and then set a temporary width and height to then autofit based on all the content in the worksheet.

Windows

VB
Sub AutoFit()
'
' AutoFit Macro
' Resize the column width to better contain the content.
'
' Keyboard Shortcut: Ctrl+d
'
Cells.Select
Selection.ColumnWidth = 95
Selection.RowHeight = 95
Selection.Columns.AutoFit
Selection.Rows.AutoFit
Range("A1").Select
End Sub
macOS
VB
Sub AutoFit()
'
' AutoFit Macro
' Resize the column width to better contain the content.
'
' Keyboard Shortcut: Ctrl+e
'
Cells.Select
Range("A2").Activate
Selection.ColumnWidth = 100
Selection.RowHeight = 100
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlTop
.WrapText = True
.ShrinkToFit = True
End With
Selection.Rows.AutoFit
Selection.Columns.AutoFit
Range("A1").Select
End Sub

AutoFitHeight() is designed to run in your Personal.xlsb with a keyboard function of Ctrl+e to select all columns and rows and then autofit the height based on the all the content in the worksheet

VB
Sub AutoFitHeight()
'
' AutoFitHeight Macro
'
' Keyboard Shortcut: Ctrl+e
'
Cells.Select
Selection.Rows.AutoFit
Range("A1").Select
End Sub
Originally Posted on January 26, 2015
Last Updated on December 7, 2025
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.