Autofit Columns VBA

dannyok90

Board Regular
Joined
Aug 30, 2016
Messages
115
Hi all,


Just wondering if there is a way to autofit columns but keep its current size if the new contents don't extend beyond its current width?


Thanks,
Dan
 

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.
Code:
Sub a()
Dim cw As Variant
cw = Columns("A").ColumnWidth
Columns("A").AutoFit
    If Columns("A").ColumnWidth < cw Then
        Columns("A").ColumnWidth = cw
    End If
End Sub

This can only be applied one column at a time, since some columns may be wider than others or may have different original settings than others. However, it can be put into a loop to evaluate multiple columns one at a time.
 
Last edited:
Upvote 0
A slight variation of JLGWhiz's code to make it work with any column: Copy and paste this macro into the worksheet code module. Do the following: right click the tab name for your sheet and click 'View Code'. Paste the macro into the empty code window that opens up. Close the code window to return to your sheet.
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    Application.ScreenUpdating = False
    Dim cw As Long
    cw = Target.ColumnWidth
    With Columns(Target.Column)
        .AutoFit
        If .ColumnWidth < cw Then
            .ColumnWidth = cw
        End If
    End With
    Application.ScreenUpdating = True
End Sub
 
Upvote 0
Nice one Thanks Guys!

Mumps if I wanted to apply this to the whole workbook, would it be as simple as changing it to a workbook_change event and putting it in the workbook module?

Dan
 
Upvote 0
Glad we could help and yes, that is correct but it's a Workbook_SheetChange event. :)
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,985
Messages
6,122,606
Members
449,089
Latest member
Motoracer88

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