How to Autofit Column Widths (VBA)

Send Us a Sign! (Contact Us!)
--> (Word) --> (PDF) --> (Epub) --> (Text)
--> (XML) --> (OpenOffice) --> (XPS) --> (MHT)

Somebody could ask for VBA code that will automatically adjust column widths to fit the cell contents. It's actually very simple and all you need is one function call. You simply need to call the AutoFit method.

Sub AutoFitAllColumns()
ActiveSheet.UsedRange.Columns.AutoFit
End Sub

If you wanted to autofit the row heights, you'll need something like this:

Sub AutoFitAllRows()
ActiveSheet.UsedRange.Rows.AutoFit
End Sub

Just note that for autofit of rows to work, you'll need to have the "Wrap Text" setting turned on.

[tweet]

To do that, you need to select the range you want to autofit and from the main menu, go to Format->Cells. Then in the Alignment tab, tick the checkbox for "Wrap Text".

SOURCE

LINK

LANGUAGE
ENGLISH