Excel VBA Wrap Text and AutoFit: A Complete Guide
In this article
To wrap text and autofit rows in Excel using VBA, you must set the WrapText property of the range to True and then call the AutoFit method on the Rows collection. This ensures that long strings of text do not overflow into adjacent cells or get cut off, but instead expand vertically to fit the column width. This is essential for creating professional reports where data length varies significantly across entries.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- A workbook containing data that requires formatting.
- The Developer tab enabled in the Excel Ribbon (if not visible, right-click any tab, select Customize the Ribbon, and check the Developer box).
- Basic familiarity with opening the Visual Basic Editor (VBE).
Step-by-Step
- Open the Visual Basic Editor: Press
Alt + F11on your keyboard. This shortcut opens the VBE window, which is the environment where all VBA code is written and managed. - Insert a New Module: In the top menu, go to
Insert>Module. This creates a blank space where you can write your macro. Writing code in a module ensures the macro is available to the entire workbook rather than being tied to a specific sheet. - Write the Macro Procedure: Type the following code into the module window:
Sub FormatTextAndRows() Dim ws As Worksheet Set ws = ThisWorkbook.ActiveSheet With ws.UsedRange .WrapText = True .Rows.AutoFit End With End SubIn this code,ws.UsedRangetargets every cell that contains data. TheWrapText = Truecommand tells Excel to wrap text within the cell boundaries, and.Rows.AutoFitadjusts the row height to accommodate the wrapped content. - Define a Specific Range (Optional): If you do not want to format the entire sheet, replace
ws.UsedRangewith a specific range, such asws.Range("A1:C10"). This prevents the macro from affecting cells you wish to leave untouched. - Run the Macro: You can run the code directly from the VBE by pressing
F5or clicking the green "Run" arrow in the toolbar. Alternatively, go back to your Excel sheet, pressAlt + F8, selectFormatTextAndRowsfrom the list, and clickRun. - Save the Workbook: Because this file now contains a macro, you must save it as an
Excel Macro-Enabled Workbook (.xlsm). If you save it as a standard.xlsxfile, all your VBA code will be permanently deleted.
Common Mistakes
One of the most frequent errors is attempting to AutoFit columns after wrapping text. If you wrap text and then use Columns.AutoFit, Excel will expand the column width to fit the longest string of text on a single line, effectively undoing the visual purpose of the wrap. Always set your column widths first, then apply wrap text, and finally autofit the rows.
Another common mistake is forgetting to specify the worksheet. Using ActiveSheet is convenient, but if the macro is triggered while a different sheet is selected, it will format the wrong data. For more robust code, use the specific sheet name: Set ws = ThisWorkbook.Sheets("DataSheet").
Users often overlook the impact of merged cells. VBA's AutoFit method does not work on rows that contain merged cells. If your data contains merged cells, the AutoFit command will execute without an error, but the row height will remain unchanged, leaving your wrapped text partially hidden.
Tips
To make your macro more efficient, disable screen updating at the start of the code. When VBA changes cell formatting, Excel tries to redraw the screen for every single change, which can cause flickering and slow down the process on large datasets. Add Application.ScreenUpdating = False at the beginning and Application.ScreenUpdating = True at the end.
If you want to apply this formatting automatically whenever data is entered, move your code from a standard Module to the Worksheet_Change event. By placing the code in the sheet object under the Private Sub Worksheet_Change(ByVal Target As Range) event, Excel will automatically wrap and autofit the rows the moment a user finishes typing in a cell.
Consider combining this with a fixed column width. For example, adding ws.Columns("B").ColumnWidth = 30 before the wrap and autofit commands ensures that your report has a consistent look across different computers, regardless of the default font settings of the user opening the file.
Troubleshooting
If the rows are not adjusting their height despite the code running, first check for merged cells. As mentioned, merged cells break the AutoFit functionality. The solution is to unmerge the cells or use "Center Across Selection" (found in Format Cells > Alignment) instead of merging.
If you receive a "Run-time error 1004", ensure that the worksheet is not protected. VBA cannot modify formatting or row heights on a protected sheet. You must add a line of code to unprotect the sheet using ws.Unprotect Password:="yourpassword" at the start of the macro and reprotect it at the end.
If the text is still cutting off at the bottom of the cell, it may be due to a manually set row height that is overriding the autofit. While AutoFit usually fixes this, sometimes clearing the row height first or ensuring the cell alignment is set to xlVAlignCenter or xlBottom helps the rendering engine calculate the height more accurately.
Frequently Asked Questions
Does AutoFit work on merged cells?
No, the standard AutoFit method in VBA does not support merged cells. You must either unmerge the cells or use a complex custom function to calculate the required height based on the character count and column width.
Can I wrap text for only one specific column?
Yes. Instead of using UsedRange, specify the column. For example, use ws.Columns("B").WrapText = True followed by ws.Columns("B").Rows.AutoFit.
Why does my column width change when I run the macro?
If you used Columns.AutoFit instead of Rows.AutoFit, Excel will widen the column to fit the text. Ensure you are targeting the Rows collection to keep the width constant and increase the height.
Will this macro work on a Mac?
Yes, the WrapText and AutoFit properties are standard across both Windows and Mac versions of Excel VBA, though the keyboard shortcuts to open the editor may differ.
How do I stop the screen from flickering during the process?
Use Application.ScreenUpdating = False at the start of your sub-procedure. This prevents Excel from refreshing the visual display until the code has finished executing.
What is the difference between .WrapText and .AutoFit?
WrapText is a property that allows text to move to a new line within a cell. AutoFit is a method that adjusts the size of the row or column to fit the existing content. You need both to ensure wrapped text is actually visible.