Auto resize columns as you type
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all columns manually by press with left mouse button oning on the column header next to column A and then double press with left mouse button on with left mouse button on any of the delimiting column lines.
Double-press with left mouse button oning on the column next to column A selects all cells on the worksheet, double-press with left mouse button oning on any of the delimiting column lines resizes all columns containing data so it fits accordingly.
You can also press short-cut keys CTRL + A in order to select all cells on the worksheet. Note that the selected cell must be empty before you press CTRL + A. If not, a cell range containing contiguous adjacent non-empty cells will be selected.
There is a short-cut for auto adjusting column widths as well, simply press Alt + H + O + I. Make sure you have selected the cells you want to to auto adjust before pressing the short-cut keys.
You can, however, create an Event that does this for you automatically. 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 instantly.
Example,
The Event code displayed below is not placed in a regular code module, this event code is placed in the Workbook module, event code is rund when a specific thing happens.
For example, a cell is selected, a worksheet is activated, a workbook is closed, a cell value has changed etc. All these actions can trigger an Event, which Event is determined by the name of the macro.
VBA code
'The WorkbookSheetChange event is run if any of the cells in the workbook changes Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) 'Don't show changes made to the worksheet Application.ScreenUpdating = False 'Go through each cell that has been changed For Each Value In Target.Columns 'Auto resize column using the Autofit method Worksheets(Sh.Name).Columns(Value.Column).AutoFit 'Continue with next cell that has changed Next Value 'Show changes to the user Application.ScreenUpdating = True End Sub
The Target parameter is a range object containing the cell or cells that have been changed, the Sh parameter contains the worksheet object of the changed cells.
The ScreenUpdating property allows you to perform changes to the workbook without showing the result until all changes have been made, this makes the code run faster and smoother.
Where to copy code?
- Press Alt + F11 to open the VBA Editor.
- Double-press with left mouse button on ThisWorkbook in Project Explorer
- Copy VBA code
- Paste to the code module
- Exit VBA editor and return to Excel
Final thoughts
The downside with this approach is that you lose the ability to undo any changes you make, there is, however, a solution to that: Generic undo routine for VBA
If you want to use two lines in one cell simply press Alt+Enter where you want the text to be split.
Macro category
This article demonstrates how to add or remove a value in a regular drop down list based on a list […]
In this tutorial, I am going to show you how to add values to a drop down list programmatically in […]
This article demonstrates how to place values automatically to a table based on two conditions using a short macro. Cell […]
This tutorial shows you how to add a record to a particular worksheet based on a condition, the image above […]
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]
In this small tutorial, I am going to show you how to create basic data entry with a small amount […]
Here is my contribution to all excel calendars out there. My calendar is created in Excel 2007 and uses both […]
In this article I will demonstrate how to quickly change chart data range utilizing a combobox (drop-down list). The above […]
The image above shows a chart populated with data from an Excel defined Table. The worksheet contains event code that […]
What's on this page Press with left mouse button on a specific cell to hide/show entire column Where to put […]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]
In this blog post, I will demonstrate some VBA copying techniques that may be useful if you don't know the […]
I will in this article demonstrate a macro that automatically opens all workbooks in a folder and subfolders, one by […]
I will in this article demonstrate a macro that copies criteria from one Excel Table and applies them to another […]
This article demonstrates several VBA macros, they will save you time if you have lots of worksheets. The first macro […]
I will in this article demonstrate a macro that counts how many times a specific text string is found in […]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]
Question: hi all, thanks for the great formula/array formula. it works great. lately, i noticed that the array formula will […]
It can sometimes be helpful having a large cell value in a comment. You can then easily hover over cell […]
This article demonstrates a macro that inserts new worksheets based on names in a cell range. The cell range may […]
Save links to your favorite macros in a personal tab on the ribbon for easy access and become more productive. […]
In a previos post:Excel vba: Save invoice data we added/copied data between sheets. This post describes how to overwrite existing […]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]
In this article, I am going to demonstrate a simple workbook where you can create or delete projects and add […]
This article demonstrates a macro that returns cell references for cell ranges populated with values on a worksheet. Jinesh asks: […]
In this post I am going to demonstrate how to quickly apply a filter to a table. I am using […]
In this tutorial, I am going to demonstrate how to filter an Excel define Table through a VBA macro. How it […]
This article describes different ways to locate literal or hardcoded values in formulas. The image above shows the result from […]
This post Find the longest/smallest consecutive sequence of a value has a few really big array formulas. Today I would like to […]
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]
This article demonstrates event code combined with Conditional Formatting that highlights overlapping date ranges based on the selected date range. […]
This post describes how to add a new custom-built item to the shortcut menu in Excel, when you press with right […]
The Quick Access Toolbar is located at the very top of your Excel window, I highly recommend that you place your […]
Rahul asks: I want to know how to create a vlookup sheet, and when we enter a name in a […]
This article demonstrates a formula and a VBA macro that returns every n-th row from a given cell range. The […]
The image above demonstrates a macro linked to a button. Press with left mouse button on the button and the […]
If you try to copy multiple cell ranges on a worksheet that don't have the same number of rows or […]
Did you know that you can select all cells containing comments in the current sheet? Press F5, press with left […]
This article describes how to create an interactive chart, the user may press with left mouse button on a button […]
Today I would like to share with you these small event handler procedures that make it easier for you to […]
This article demonstrates how to automatically create log entries when a workbook opens or closes using event code. Column A […]
In this smaller example, column D (Category) has empty cells, shown in the picture above. If your column contains thousands of […]
Macros and custom functions are great, they can automate many tedious tasks. To have them available whenever you need them, […]
This article demonstrates macros that save worksheets to a single pdf file. What's on this webpage Export all worksheets in […]
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]
This article demonstrates how to insert and use a scroll bar (Form Control) in Excel. It allows the user to […]
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]
In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and […]
The following macro inserts a new sheet to your workbook and lists all Excel defined Tables and corresponding Table headers […]
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]
This article demonstrates how to move a shape, a black arrow in this case, however, you can use whatever shape […]
This article demonstrates a User Defined Function (UDF) that multiplies numbers in each row with the remaining rows in a […]
To be able to use a Pivot Table the source data you have must be arranged in way that a […]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]
This article explains how to set up a workbook so a macro is run every time you open the workbook. […]
In this tutorial I am going to explain how to: Create a combo box (form control) Filter unique values and […]
In this post I am going to demonstrate two things: How to populate a combobox based on column headers from […]
Excel defined Tables, introduced in Excel 2007, sort, filter and organize data any way you like. You can also format […]
This post demonstrates how to: Insert a button to your worksheet Assign a macro to the button Create a basic […]
This article demonstrates a macro that allows you to rearrange and distribute concatenated values across multiple rows in order to […]
In this post I am going to rearrange values from a list into unique columns. Before: After: The code Get […]
This article demonstrates how to run a VBA macro using a Drop Down list. The Drop Down list contains two […]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]
This article demonstrates a macro that automatically applies a filter to an Excel defined Table based on the result from […]
This post demonstrates how to view saved invoices based on the invoice number using a userform. The userform appears when the […]
This post demonstrates a macro that automatically selects cell A1 on each sheet right before you close a workbook. The […]
This article explains how to hide a specific image in Excel using a shape as a button. If the user […]
This article demonstrates a macro and a formula that allows you to sort delimited data in a cell or cell […]
This article demonstrates how to sort a specific column in an Excel defined Table based on event code. The event […]
In this post I am going to show how to create a new sheet for each airplane using vba. The […]
This article demonstrates how the user can run a macro by press with left mouse button oning on a button, […]
This blog post describes how to insert qualifers to make "text to columns" conversion easier. Example I copied a table from […]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]
There are two different kinds of text boxes, Form controls and ActiveX Controls. Form controls can only be used on […]
Excel categories
20 Responses to “Auto resize columns as you type”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
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.
Oops,
forgot to add,
would this be included in the first code or should it be a separate code?
Cyril,
You can select "Format rows" and "Format columns" when you protect a sheet.
Now you can use the macro in a protected sheet.
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.
Cyril,
Try this code:
Thanks Oscar!
Could this work for rows? I have a column I need to stay the same size but I need the rows to be re-sized as the user types. Can you help?
Yogi,
Yes!
Get the Excel *.xlsm file
Auto-resize-rows.xlsm
Hi! How can I make it work for selected worksheets rather than whole workbook? I need to have one or two worksheets where the column width is set manually. Many thanks for your help in advance.
Justine,
1. Press with right mouse button on a sheet name
2. Press with left mouse button on "View Code.."
3. Copy / Paste the code below
4. Return to excel (Alt + Q)
Thank you so much, this is very helpful. I have two worksheets where I already have a code for automatic sorting, and when I paste this second code to the editor then try to add new data I get an error message - Compile error: Ambiguous name detected: Worksheet_Change. Any idea what am I doing wrong? I'll be most grateful for your help.
Justine,
It seems like you have two Worksheet_Change subroutines. You can only have one.
This is great. What change needs to be done in order for it to work with dynamic data (like data populated with index match or vlookup or lookup and contat formula you have). I have my version from your replies as below. Instead of change I thought triggering event with Calculate would work, but it did not.
Also we have about 2000 rows loading dynamically and do not want to overload excel. Thanks a lot in advance.
Private Sub Worksheet_Calculate(ByVal Target As Range)
Application.ScreenUpdating = False
Worksheets(Sh.Name).Unprotect Password:="Password"
On Error Resume Next
For Each Value In Target.Columns
Worksheets(Sh.Name).Rows(Value.Column).AutoFit
Next Value
On Error GoTo 0
Worksheets(Sh.Name).Protect Password:="Password"
Application.ScreenUpdating = True
End Sub
I meant "Lookup_concat" user formula that you mentioned in other tutorial.
Why am I getting "variable not defined" error on first line of the code?
Andrew,
Did you put the code in the workbook module?
Oscar,
This works perfectly for resizing the columns, so thanks for that! I just noticed, though, that the sheet no longer allows for an 'Undo'. Ctrl-Z just gives me a noise indicating that I did something wrong, and the 'Undo' arrow is grayed out. Is there something I can do to fix that? FYI, I'm using Excel 2013.
Thanks,
Zach
Zach
Short answer:
No, that is a disadvantage with the macro.
Long answer:
https://stackoverflow.com/questions/24185942/save-undo-stack-during-macro-run
https://www.jkp-ads.com/Articles/UndoWithVBA00.asp
Thanks for your support Oscar.
In case i Want to apply this formula but to just specific columns... what do I have to change or add on this 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).Rows(Value.Column).AutoFit
Next Value
Application.ScreenUpdating = True
End Sub
So far this works great for me, but how do you also have it adjust the height as well as the width in the VBA? So far it just the width. I have sheet with several columns and cells that auto fill from what is selected in the drop down list.