Problem : Excel VBA Autofit column widths to a maximum width and then override specific columns to a second set column width
I have a worksheet where I need to firstly autofit the column widths of the data (excluding the first row which is a header) but limit the maximum width of the auto fit to 25. Then in specified columns I need to set the column width is set to 40. All cells in the spreadsheet (header included) need to have the text wrap within the columns.
Appreciate your help!
Solution: Excel VBA Autofit column widths to a maximum width and then override specific columns to a second set column width
Sub DoAutofitAndWrap()
Dim x As Range
Worksheets(“Sheetname”).Select
ActiveSheet.Columns.AutoFit
ActiveSheet.Cells.WrapText = True
For Each x In Rows(“1:1”).Cells
If x.ColumnWidth > 25 Then x.ColumnWidth = 25
If x.Column = 3 Or x.Column = 9 Then x.ColumnWidth = 40 ‘modify this line for the columns that get 40
Next
End Sub