Questions

Answer for:

EXCEL - text alignment

Message 2 of 2

View entire thread
+
0 Votes
Darryl~

Here is a method to make all columns, in all worksheets in the activeworkbook, autofit if data is entered that exceeds the current column width.

Copy the following event handler to the clipboard (highlight the entire code, right click inside the highlighted area, and 'Copy'):

Private Sub Workbook_SheetChange(ByVal Sh As Object, _
ByVal Target As Range)
Dim actCol, curCol
actCol = Target.Column
If actCol > 52 Then
curCol = Chr(Int((actCol - 1) / 52) 64) & _
Chr(Int((actCol - 27) / 26) 64) & _
Chr(Int((actCol - 27) Mod 26) 65)
ElseIf actCol > 26 Then
curCol = Chr(Int((actCol - 1) / 26) 64) & _
Chr(Int((actCol - 1) Mod 26) 65)
Else
curCol = Chr(actCol 64)
End If
Columns(curCol & ":" & curCol).AutoFit
End Sub

With your workbook open, press ALT F11 (Function Key F11)

Double click 'THIS WORKBOOK' in the Microsoft Excel VBA Project objects in the upper left quadrant.

Paste the event handler into the white editing area to the right (right click inside the area and 'Paste').

Close the VBE (red button w/white 'x' --- top right).

Save the workbook.

Enter data in any column, in any sheet in the workbook, and if it exceeds the column width the column will autofit once you select a cell in a different column.