How to autofit column width up to maximum size?

omnipotentmero

New Member
Joined
Feb 16, 2012
Messages
10
Hey all, I am looking for a way to automate my worksheet formatting, but I don't know enough about excel's VBA macros to write one myself. What I am looking to do is to autofit all column widths on a given worksheet, but to limit the maximum size to 50.

I often deal with 30+ columns that have a mix of relatively narrow data (date, times, IP address...) and wide data (long URLS, or block of text). I want to be able to shrink the narrow fields to their most efficient use of space, truncate everything else so it does not visually take up the entire screen.

Thanks in advance for your help.
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
1. Press Alt+F11
2. Click on Insert > Module
3. In the new Window that should have opened copy this code:
'-------------------------------------------
Sub mAutoWidth()
Dim mCell As Range
Application.ScreenUpdating = False

For Each mCell In ActiveSheet.UsedRange.Rows(1).Cells
mCell.EntireColumn.AutoFit
If mCell.EntireColumn.ColumnWidth > 50 Then _
mCell.EntireColumn.ColumnWidth = 50
Next mCell

Application.ScreenUpdating = True
End Sub
'-------------------------------------------
4. Close the VBA editor with Alt+F4
5. Back in Excel use Alt + F8 to see the list of available Macros
6. Choose mAutoWidth and click Run
 
Last edited:
Upvote 0

Forum statistics

Threads
1,217,317
Messages
6,135,833
Members
449,965
Latest member
Ckl43

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top