Auto resize columns as you type
Let me show you how to create self adjusting columns in excel with a few lines of vba code.
Example,
You can also copy and paste cells and the columns resize automatically .
Example,
VBA code
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Application.ScreenUpdating = False
For Each Value In Target.Columns
Worksheets(Sh.Name).Columns(Value.Column).AutoFit
Next Value
Application.ScreenUpdating = True
End SubWhere to copy code?
- Press Alt + F11
- Double click ThisWorkbook in Project Explorer
- Copy vba code
- Paste in code module
Download excel 2007 *xlsm file









February 11th, 2012 at 3:10 am
Oscar,
what code would you suggest in order to allow column resizing in a protected worksheet?
whereas some cells are locked.
would still the vba encounter a Run-time error '424' if a line was added to "bypass" the protection?
(un protect, modify,re-protect)
such as:
Sheets(“Sheet1″).Unprotect Password:=” whatever ”
PROCEDURE
Sheets(“Sheet1).Protect Password:=” whatever “
with the risk of having the sheet unprotected if the procedure fails...
or something like
Private Sub Workbook_Open()
Sheets (" sheetname ") .protect _
Password:=" whatever", _
UserInterfaceOnly:=True
End Sub
Thanks.
February 11th, 2012 at 3:12 am
Oops,
forgot to add,
would this be included in the first code or should it be a separate code?
February 16th, 2012 at 8:40 am
Cyril,
You can select "Format rows" and "Format columns" when you protect a sheet.
Now you can use the macro in a protected sheet.
February 16th, 2012 at 9:36 am
Yes... true.
although I locked the sheet to limit the width... I have many users and some tend to be "artistic" and revamp the files.
Thanks for the reminder.
February 20th, 2012 at 1:54 pm
Cyril,
Try this code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) Application.ScreenUpdating = False Worksheets(Sh.Name).Unprotect Password:="whatever" On Error Resume Next For Each Value In Target.Columns Worksheets(Sh.Name).Columns(Value.Column).AutoFit Next Value On Error GoTo 0 Worksheets(Sh.Name).Protect Password:="whatever" Application.ScreenUpdating = True End SubFebruary 21st, 2012 at 1:32 am
Thanks Oscar!