Переноса текста по словам в ячейках диапазона на рабочем листе Excel из кода VBA. Свойство WrapText объекта Range, возвращаемые значения. Примеры.
Range.WrapText – это свойство, которое возвращает или задает значение типа Variant, указывающее, переносится ли текст в ячейках диапазона на новые строки, если длина текста превышает ширину ячейки.
Текст в ячейках переносится по словам. Если слово не умещается в ячейке целиком, происходит перенос части слова. Обычно, высота строки рабочего листа автоматически подбирается под ячейку с максимальным количеством строк, образовавшихся в результате переноса текста.
Синтаксис
Expression.WrapText
Expression – выражение (переменная), возвращающее объект Range.
Значения
Значения, которые возвращает свойство Range.WrapText:
Параметр | Значение |
---|---|
True | Во всех ячейках указанного диапазона включен перенос текста на новые строки. |
False | Во всех ячейках указанного диапазона отключен перенос текста на новые строки. |
Null | В указанном диапазоне присутствуют пустые ячейки, или есть ячейки как с переносом текста, так и без переноса. |
Примеры
Пример 1
Указание программе Microsoft Excel, что она должна или не должна переносить текст в ячейках заданного диапазона:
‘переносить текст в активной ячейке ActiveCell.WrapText = True ‘переносить текст во всех ячейках заданного диапазона Range(«A1:F20»).WrapText = True ‘не переносить текст в ячейке Cells(1, 5) Cells(1, 5).WrapText = False ‘не переносить текст во всех ячейках выбранного диапазона Selection.WrapText = False |
Пример 2
Присвоение значения, возвращаемого свойством Range.WrapText, переменной:
Dim a As Variant a = Range(«B2»).WrapText a = Rows(«1:2»).WrapText |
Пример 3
Просмотр значения, возвращаемого свойством Range.WrapText, с помощью информационного окна MsgBox:
If Not Selection.WrapText = Null Then MsgBox Selection.WrapText Else MsgBox «Null» End If |
Условие необходимо из-за того, что MsgBox не может отобразить значение Null
– возникает ошибка. Поэтому, когда свойство Range.WrapText = Null
, мы задаем в качестве аргумента функции MsgBox – строку «Null».
Home / VBA / VBA Wrap Text (Cell, Range, and Entire Worksheet)
In VBA, there is a property called “WrapText” that you can access to apply wrap text to a cell or a range of cells. You need to write code to turn it ON or OFF. It’s a read and writes property, so you can apply it, or you can also get it if it’s applied on a cell.
In this tutorial, we will look at different ways of applying wrap text using a VBA code.
Wrap Text to a Cell using VBA
Use the following steps to apply Wrap Text using a VBA Code.
- Define the cell where you want to apply the wrap text using the range property.
- Type a dot to see the list of the properties and methods for that cell.
- Select the “WrapText” property from the list.
- Enter the equals sign “=” and type TRUE to turn on the wrap text.
Sub vba_wrap_text()
Range("A1").WrapText = True
End Sub
You can also specify a cell using the following way.
Cells(1, 1).WrapText = True
Wrap Text to a Range of Cells
And if you want to apply wrap text to an entire range then you need to specify the range instead of a single cell.
Range("A1:A5").WrapText = True
You can also apply it to the used range (selection of the worksheet where you have entered data) by using the “UsedRange” property.
Worksheets("Sheet1").UsedRange.WrapText = True
ActiveSheet.UsedRange.WrapText = True
In the above code’s first line, you have specified the worksheet and then the “UsedProperty” to wrap the text. In the second line, you have the active sheet’s used range. But both lines work in the same way.
Here are a few more examples that you need to know:
- Non-continues cells
- Entire Row
- Entire Column
- Named Range
Range("A1:A10,C1:C10").WrapText = True
Range("A:A").WrapText = True
Range("1:1").WrapText = True
Range("myRange").WrapText = True
To refer to the entire worksheet you need to use the Cells property as you have in the following code.
Cells.WrapText = True
Worksheets("Sheet1").Cells.WrapText = True
The first line of code refers to the active sheet and the second line to the worksheet “Sheet1”. You can also use a loop using FOR EACH (For Next) to loop through all the worksheets of the workbook and apply the wrap text on all the cells.
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Cells.WrapText = True
Next ws
In the above code, you have “ws” as a variable and then For Each Loop loops through all the worksheets from the workbook and applies to wrap text to the entire worksheet using Cells.
Turn OFF WrapText
As you have seen you need to turn on the WrapText property, and in the same way you can turn it off by using add declaring FALSE.
Range("A1").WrapText = False
Note: There’s one thing you need to understand if you have a value in a cell and the width of the cells is enough to store that value, then even if you apply wrap text, Excel won’t shift the content to the next line.
More Tutorials
- Count Rows using VBA in Excel
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- SELECT ALL the Cells in a Worksheet using a VBA Code
- ActiveCell in VBA in Excel
- Special Cells Method in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Check IF a Cell is Empty + Multiple Cells
⇠ Back to What is VBA in Excel
Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes
Return to VBA Code Examples
In this tutorial, you will learn about how to enable or disable Wrap Text in Excel using VBA.
Wrapping Text using VBA
You wrap the text in a cell or range by setting the Range.WrapText Property of the Range object to True. The following code will wrap the text in cell A1:
Worksheets("Sheet1").Range("A1").WrapText = True
The result is:
You can Wrap a larger range of cells as well:
Range("A1:A10").WrapText = True
Disabling Wrapping in a Cell using VBA
You can disable text wrapping in a certain cell or range using VBA. The following code will disable text wrapping in cell B2:
Range("B2").WrapText = False
Disabling Wrapping in An Entire Worksheet
You can disable text wrapping in all the cells on a worksheet using VBA. The following code will allow you to disable text wrapping in all the cells in the ActiveSheet:
Sub DisableWrapText ()
Cells.WrapText = False
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Range.WrapText property (Excel) |
vbaxl10.chm144221 |
vbaxl10.chm144221 |
excel |
Excel.Range.WrapText |
5e61b704-af16-7bad-5eeb-f163e3035513 |
05/11/2019 |
medium |
Range.WrapText property (Excel)
Returns or sets a Variant value that indicates if Microsoft Excel wraps the text in the object.
Syntax
expression.WrapText
expression A variable that represents a Range object.
Remarks
This property returns True if text is wrapped in all cells within the specified range, False if text is not wrapped in all cells within the specified range, or Null if the specified range contains some cells that wrap text and other cells that don’t.
Microsoft Excel will change the row height of the range, if necessary, to accommodate the text in the range.
Example
This example formats cell B2 on Sheet1 so that the text wraps within the cell.
Worksheets("Sheet1").Range("B2").Value = _ "This text should wrap in a cell." Worksheets("Sheet1").Range("B2").WrapText = True
[!includeSupport and feedback]
Содержание
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- Wrap Text to a Cell using VBA
- Wrap Text to a Range of Cells
- Wrap Text to the Entire Worksheet
- Turn OFF WrapText
- VBA Wrap Text
- Wrapping Text using VBA
- Disabling Wrapping in a Cell using VBA
- Disabling Wrapping in An Entire Worksheet
- VBA Coding Made Easy
- VBA Code Examples Add-in
- VBA Format Cells
- Formatting Cells
- AddIndent
- Borders
- FormulaHidden
- HorizontalAlignment
- VBA Coding Made Easy
- IndentLevel
- Interior
- Locked
- MergeCells
- NumberFormat
- NumberFormatLocal
- Orientation
- Parent
- ShrinkToFit
- VerticalAlignment
- WrapText
- VBA Code Examples Add-in
- Formatting a Range of Cells In Excel VBA
- Formatting Cells Number
- General
- Number
- Currency
- Accounting
- Percentage
- Fraction
- Scientific
- Special
- Custom
- Formatting Cells Alignment
- Text Alignment
- Horizontal
- Vertical
- Text Control
- Wrap Text
- Shrink To Fit
- Merge Cells
- Right-to-left
- Text direction
- Orientation
- Font Name
- Font Style
- Font Size
- Underline
- Font Color
- Font Effects
- Strikethrough
- Subscript
- Superscript
- Border
- Border Index
- Line Style
- Line Thickness
- Line Color
- Pattern Style
- Protection
- Locking Cells
- Hiding Formulas
VBA Wrap Text (Cell, Range, and Entire Worksheet)
In VBA, there is a property called “WrapText” that you can access to apply wrap text to a cell or a range of cells. You need to write code to turn it ON or OFF. It’s a read and writes property, so you can apply it, or you can also get it if it’s applied on a cell.
In this tutorial, we will look at different ways of applying wrap text using a VBA code.
Wrap Text to a Cell using VBA
Use the following steps to apply Wrap Text using a VBA Code.
- Define the cell where you want to apply the wrap text using the range property.
- Type a dot to see the list of the properties and methods for that cell.
- Select the “WrapText” property from the list.
- Enter the equals sign “=” and type TRUE to turn on the wrap text.
You can also specify a cell using the following way.
Wrap Text to a Range of Cells
And if you want to apply wrap text to an entire range then you need to specify the range instead of a single cell.
You can also apply it to the used range (selection of the worksheet where you have entered data) by using the “UsedRange” property.
In the above code’s first line, you have specified the worksheet and then the “UsedProperty” to wrap the text. In the second line, you have the active sheet’s used range. But both lines work in the same way.
Here are a few more examples that you need to know:
- Non-continues cells
- Entire Row
- Entire Column
- Named Range
Wrap Text to the Entire Worksheet
To refer to the entire worksheet you need to use the Cells property as you have in the following code.
The first line of code refers to the active sheet and the second line to the worksheet “Sheet1”. You can also use a loop using FOR EACH (For Next) to loop through all the worksheets of the workbook and apply the wrap text on all the cells.
In the above code, you have “ws” as a variable and then For Each Loop loops through all the worksheets from the workbook and applies to wrap text to the entire worksheet using Cells.
Turn OFF WrapText
As you have seen you need to turn on the WrapText property, and in the same way you can turn it off by using add declaring FALSE.
Note: There’s one thing you need to understand if you have a value in a cell and the width of the cells is enough to store that value, then even if you apply wrap text, Excel won’t shift the content to the next line.
Источник
VBA Wrap Text
In this Article
In this tutorial, you will learn about how to enable or disable Wrap Text in Excel using VBA.
Wrapping Text using VBA
You wrap the text in a cell or range by setting the Range.WrapText Property of the Range object to True. The following code will wrap the text in cell A1:
You can Wrap a larger range of cells as well:
Disabling Wrapping in a Cell using VBA
You can disable text wrapping in a certain cell or range using VBA. The following code will disable text wrapping in cell B2:
Disabling Wrapping in An Entire Worksheet
You can disable text wrapping in all the cells on a worksheet using VBA. The following code will allow you to disable text wrapping in all the cells in the ActiveSheet:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
VBA Format Cells
In this Article
This tutorial will demonstrate how to format cells using VBA.
Formatting Cells
There are many formatting properties that can be set for a (range of) cells like this:
Let’s see them in alphabetical order:
AddIndent
By setting the value of this property to True the text will be automatically indented when the text alignment in the cell is set, either horizontally or vertically, to equal distribution (see HorizontalAlignment and VerticalAlignment).
Borders
You can set the border format of a cell. See here for more information about borders.
As an example you can set a red dashed line around cell B2 on Sheet 1 like this:
You can adjust the cell’s font format by setting the font name, style, size, color, adding underlines and or effects (strikethrough, sub- or superscript). See here for more information about cell fonts.
Here are some examples:
FormulaHidden
This property returns or sets a variant value that indicates if the formula will be hidden when the worksheet is protected. For example:
HorizontalAlignment
This property cell format property returns or sets a variant value that represents the horizontal alignment for the specified object. Returned or set constants can be: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight, xlFill, xlCenterAcrossSelection. For example:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
IndentLevel
It returns or sets an integer value between 0 and 15 that represents the indent level for the cell or range.
Interior
You can set or get returned information about the cell’s interior: its Color, ColorIndex, Pattern, PatternColor, PatternColorIndex, PatternThemeColor, PatternTintAndShade, ThemeColor, TintAndShade, like this:
Locked
This property returns True if the cell or range is locked, False if the object can be modified when the sheet is protected, or Null if the specified range contains both locked and unlocked cells. It can be used also for locking or unlocking cells.
This example unlocks cells A1:B2 on Sheet1 so that they can be modified when the sheet is protected.
MergeCells
Set this property to True if you need to merge a range. Its value gets True if a specified range contains merged cells. For example, if you need to merge the range of C5:D7, you can use this code:
NumberFormat
You can set the number format within the cell(s) to General, Number, Currency, Accounting, Date, Time, Percentage, Fraction, Scientific, Text, Special and Custom.
Here are the examples of scientific and percentage number formats:
NumberFormatLocal
This property returns or sets a variant value that represents the format code for the object as a string in the language of the user.
Orientation
You can set (or get returned) the text orientation within the cell(s) by this property. Its value can be one of these constants: xlDownward, xlHorizontal, xlUpward, xlVertical or an integer value from –90 to 90 degrees.
Parent
This is a read-only property that returns the parent object of a specified object.
ShrinkToFit
This property returns or sets a variant value that indicates if text automatically shrinks to fit in the available column width.
VerticalAlignment
This property cell format property returns or sets a variant value that represents the vertical alignment for the specified object. Returned or set constants can be: xlCenter, xlDistributed, xlJustify, xlBottom, xlTop. For example:
WrapText
This property returns True if text is wrapped in all cells within the specified range, False if text is not wrapped in all cells within the specified range, or Null if the specified range contains some cells that wrap text and other cells that don’t.
For example, if you have this range of cells:
this code below will return Null in the Immediate Window:
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Formatting a Range of Cells In Excel VBA
Formatting Cells Number
General
Number
Currency
Accounting
Percentage
Fraction
Scientific
Special
Custom
Formatting Cells Alignment
Text Alignment
Horizontal
The value of this property can be set to one of the constants: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight.
The following code sets the horizontal alignment of cell A1 to center.
Vertical
The value of this property can be set to one of the constants: xlBottom, xlCenter, xlDistributed, xlJustify, xlTop.
The following code sets the vertical alignment of cell A1 to bottom.
Text Control
Wrap Text
This example formats cell A1 so that the text wraps within the cell.
Shrink To Fit
This example causes text in row one to automatically shrink to fit in the available column width.
Merge Cells
This example merge range A1:A4 to a large one.
Right-to-left
Text direction
The value of this property can be set to one of the constants: xlRTL (right-to-left), xlLTR (left-to-right), or xlContext (context).
The following code example sets the reading order of cell A1 to xlRTL (right-to-left).
Orientation
The value of this property can be set to an integer value from –90 to 90 degrees or to one of the following constants: xlDownward, xlHorizontal, xlUpward, xlVertical.
The following code example sets the orientation of cell A1 to xlHorizontal.
Font Name
The value of this property can be set to one of the fonts: Calibri, Times new Roman, Arial.
The following code sets the font name of range A1:A5 to Calibri.
Font Style
The value of this property can be set to one of the constants: Regular, Bold, Italic, Bold Italic.
The following code sets the font style of range A1:A5 to Italic.
Font Size
The value of this property can be set to an integer value from 1 to 409.
The following code sets the font size of cell A1 to 14.
Underline
The value of this property can be set to one of the constants: xlUnderlineStyleNone, xlUnderlineStyleSingle, xlUnderlineStyleDouble, xlUnderlineStyleSingleAccounting, xlUnderlineStyleDoubleAccounting.
The following code sets the font of cell A1 to xlUnderlineStyleDouble (double underline).
Font Color
The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.
To assist you with specifying the color of anything, the VBA is equipped with a function named RGB. Its syntax is:
This function takes three arguments and each must hold a value between 0 and 255. The first argument represents the ratio of red of the color. The second argument represents the green ratio of the color. The last argument represents the blue of the color. After the function has been called, it produces a number whose maximum value can be 255 * 255 * 255 = 16,581,375, which represents a color.
The following code sets the font color of cell A1 to vbBlack (Black).
The following code sets the font color of cell A1 to 0 (Black).
The following code sets the font color of cell A1 to RGB(0, 0, 0) (Black).
Font Effects
Strikethrough
True if the font is struck through with a horizontal line.
The following code sets the font of cell A1 to strikethrough.
Subscript
True if the font is formatted as subscript. False by default.
The following code sets the font of cell A1 to Subscript.
Superscript
True if the font is formatted as superscript; False by default.
The following code sets the font of cell A1 to Superscript.
Border
Border Index
Using VBA you can choose to create borders for the different edges of a range of cells:
- xlDiagonalDown (Border running from the upper left-hand corner to the lower right of each cell in the range).
- xlDiagonalUp (Border running from the lower left-hand corner to the upper right of each cell in the range).
- xlEdgeBottom (Border at the bottom of the range).
- xlEdgeLeft (Border at the left-hand edge of the range).
- xlEdgeRight (Border at the right-hand edge of the range).
- xlEdgeTop (Border at the top of the range).
- xlInsideHorizontal (Horizontal borders for all cells in the range except borders on the outside of the range).
- xlInsideVertical (Vertical borders for all the cells in the range except borders on the outside of the range).
Line Style
The value of this property can be set to one of the constants: xlContinuous (Continuous line), xlDash (Dashed line), xlDashDot (Alternating dashes and dots), xlDashDotDot (Dash followed by two dots), xlDot (Dotted line), xlDouble (Double line), xlLineStyleNone (No line), xlSlantDashDot (Slanted dashes).
The following code example sets the border on the bottom edge of cell A1 with continuous line.
The following code example removes the border on the bottom edge of cell A1.
Line Thickness
The value of this property can be set to one of the constants: xlHairline (Hairline, thinnest border), xlMedium (Medium), xlThick (Thick, widest border), xlThin (Thin).
The following code example sets the thickness of the border created to xlThin (Thin).
Line Color
The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.
The following code example sets the color of the border on the bottom edge to green.
You can also use the RGB function to create a color value.
The following example sets the color of the bottom border of cell A1 with RGB fuction.
Pattern Style
The value of this property can be set to one of the constants:
- xlPatternAutomatic (Excel controls the pattern.)
- xlPatternChecker (Checkerboard.)
- xlPatternCrissCross (Criss-cross lines.)
- xlPatternDown (Dark diagonal lines running from the upper left to the lower right.)
- xlPatternGray16 (16% gray.)
- xlPatternGray25 (25% gray.)
- xlPatternGray50 (50% gray.)
- xlPatternGray75 (75% gray.)
- xlPatternGray8 (8% gray.)
- xlPatternGrid (Grid.)
- xlPatternHorizontal (Dark horizontal lines.)
- xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.)
- xlPatternLightHorizontal (Light horizontal lines.)
- xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.)
- xlPatternLightVertical (Light vertical bars.)
- xlPatternNone (No pattern.)
- xlPatternSemiGray75 (75% dark moiré.)
- xlPatternSolid (Solid color.)
- xlPatternUp (Dark diagonal lines running from the lower left to the upper right.)
Protection
Locking Cells
This property returns True if the object is locked, False if the object can be modified when the sheet is protected, or Null if the specified range contains both locked and unlocked cells.
The following code example unlocks cells A1:B22 on Sheet1 so that they can be modified when the sheet is protected.
Hiding Formulas
This property returns True if the formula will be hidden when the worksheet is protected, Null if the specified range contains some cells with FormulaHidden equal to True and some cells with FormulaHidden equal to False.
Don’t confuse this property with the Hidden property. The formula will not be hidden if the workbook is protected and the worksheet is not, but only if the worksheet is protected.
The following code example hides the formulas in cells A1 and C1 on Sheet1 when the worksheet is protected.
Источник