Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-size column-width in Excel during text entry

I usually try to avoid VBA in Excel, but it would be convenient to be able to type text into a cell, and have its column get wider or narrower to accommodate the text remaining as it's entered or deleted.

This would be subject, of course, to the lengths of the text in the other cells in the column.

'Auto-fit as you type', I guess you might call it.

Is there an easy way to do this in a suitable handler?

like image 733
ChrisA Avatar asked Jan 12 '10 10:01

ChrisA


People also ask

How do you make Excel Cells expand to fit text automatically while typing?

On the Home tab, in the Cells group, click Format. Under Cell Size, do one of the following: To automatically adjust the row height, click AutoFit Row Height.

How do I make Excel columns Auto fit text?

After selecting your rows or columns, in Excel's ribbon at the top, click the “Home” tab. On the “Home” tab, in the “Cells” section, click the “Format” option. In the “Format” menu, if you'd like to autofit your columns, then choose the “AutoFit Column Width” option.


1 Answers

I'm not sure if there is a way to do it while your typing. I think excel generally stretches the cell view to display all the text before it fires the worksheet_change event.

This code will resize the column after you have changed and moved the target to a new range. Place it in the worksheet module.

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim nextTarget As Range

    Set nextTarget = Range(Selection.Address) 'store the next range the user selects

    Target.Columns.Select 'autofit requires columns to be selected
    Target.Columns.AutoFit

    nextTarget.Select
End Sub

If your just looking to do it for a particular column you would need to check the target column like this:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim nextTarget As Range

    Set nextTarget = Range(Selection.Address) 'store the next range the user selects

    If Target.Column = 1 Then

        Target.Columns.Select 'autofit requires columns to be selected
        Target.Columns.AutoFit

        nextTarget.Select
    End If
End Sub
like image 164
Fink Avatar answered Oct 05 '22 13:10

Fink