by Allen Wyatt
(last updated February 20, 2021)
Ken has a worksheet with over 100 columns of varying widths. To make it readable, he selects the whole worksheet (except for the header row) and uses AutoFit Column Width. Some columns have a single digit and he loses the ability to read the header. Some columns have 200+ characters, so they become too wide. Ken wonders if there is a way to set a minimum (7) and maximum (50) column width for the AutoFit function.
This cannot be done natively within Excel as there is no built-in way to set the minimum or maximum. However, it is easy enough to do using a macro. Here's an example of one that will do the trick:
Sub SetColWidths() Dim c As Range Dim iMin As Integer Dim iMax As Integer iMin = 7 iMax = 50 Application.ScreenUpdating = False For Each c In Selection.Columns c.AutoFit If c.ColumnWidth < iMin Then c.ColumnWidth = iMin If c.ColumnWidth > iMax Then c.ColumnWidth = iMax Next c Application.ScreenUpdating = True End Sub
In order to use the macro, simply select cells in the columns you want to affect (as Ken does), and then run the macro. It applies AutoFit to the columns and then steps through each one to make sure that nothing is narrow than 7 or wider than 50.
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (13825) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and Excel in Office 365.
Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing macros in all Office programs. This complete guide shows both professionals and novices how to master VBA in order to customize the entire Office suite for their needs. Check out Mastering VBA for Office 2010 today!
One way you can widen the columns in a worksheet to fit whatever is in the column is by double-clicking the right edge of ...Discover More
Need a quick way to hide and unhide columns in a worksheet? The shortcuts described in this tip can help fill the bill.Discover More
Want to automatically hide some columns that don't meet a date criterion that you set? You can't do it automatically, but ...Discover More
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.