Can someone provide an example of how to wrap text using VBA?

VBA (Visual Basic for Applications) is a programming language commonly used in Microsoft Office applications for automating tasks. One of its features is the ability to wrap text, which means breaking up long lines of text into multiple lines to fit within a specified width. This can be useful for creating visually appealing and organized documents. An example of how to wrap text using VBA would be to first select the cell or range of cells containing the text, then use the “WrapText” property and set it to True. This will automatically wrap the text within the selected cells.

Wrap Text Using VBA (With Example)


You can use the WrapText property in VBA to wrap text in specific cells of an Excel worksheet.

Here are three common ways to use this property in practice:

Method 1: Wrap Text of One Specific Cell

Sub UseWrapText()
Range("B2").WrapText = TrueEnd Sub

Method 2: Wrap Text of Cells in Specific Range

Sub UseWrapText()
Range("B2:B11").WrapText = TrueEnd Sub

Method 3: Wrap Text of All Cells in Worksheet

SubUseWrapText()
Cells.WrapText = TrueEnd Sub

The following examples show how to use each method in practice with the following dataset in Excel:

Let’s jump in!

Example 1: Wrap Text of One Specific Cell Using VBA

We can create the following macro to wrap the text in cell B2 only:

Sub UseWrapText()
Range("B2").WrapText = TrueEnd Sub

When we run this macro, we can click on cell B2 and see that the Wrap Text feature is turned on within the Alignment group of the Home tab along the top ribbon:

However, we must shorten the length of column B and expand the height of row 2 to actually see the text wrapped:

Now we can easily see that the text in cell B2 is wrapped while the text in all other cells of column B are not wrapped.

Example 2: Wrap Text of Cells in Specific Range Using VBA

We can create the following macro to wrap the text in each cell in the range B2:B11:

Sub UseWrapText()
Range("B2:B11").WrapText = TrueEnd Sub

When we run this macro, we receive the following output:

We can see that each cell in the range B2:B11 now has wrapped text.

Example 3: Wrap Text of All Cells in Worksheet Using VBA

We can create the following macro to wrap the text of every cell in a worksheet:

Sub UseWrapText()
Cells.WrapText = True
End Sub

When we run this macro, we receive the following output:

We can see that each cell in the worksheet now has wrapped text.

Note: You can find the complete documentation for the VBA WrapText property .

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

x