Wraptext vba excel описание

Переноса текста по словам в ячейках диапазона на рабочем листе 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.

  1. Define the cell where you want to apply the wrap text using the range property.
  2. Type a dot to see the list of the properties and methods for that cell.
  3. Select the “WrapText” property from the list.
  4. 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:

    Wrapping Text in VBA

    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!
    vba save as

    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]

    Содержание

    1. VBA Wrap Text (Cell, Range, and Entire Worksheet)
    2. Wrap Text to a Cell using VBA
    3. Wrap Text to a Range of Cells
    4. Wrap Text to the Entire Worksheet
    5. Turn OFF WrapText
    6. VBA Wrap Text
    7. Wrapping Text using VBA
    8. Disabling Wrapping in a Cell using VBA
    9. Disabling Wrapping in An Entire Worksheet
    10. VBA Coding Made Easy
    11. VBA Code Examples Add-in
    12. VBA Format Cells
    13. Formatting Cells
    14. AddIndent
    15. Borders
    16. FormulaHidden
    17. HorizontalAlignment
    18. VBA Coding Made Easy
    19. IndentLevel
    20. Interior
    21. Locked
    22. MergeCells
    23. NumberFormat
    24. NumberFormatLocal
    25. Orientation
    26. Parent
    27. ShrinkToFit
    28. VerticalAlignment
    29. WrapText
    30. VBA Code Examples Add-in
    31. Formatting a Range of Cells In Excel VBA
    32. Formatting Cells Number
    33. General
    34. Number
    35. Currency
    36. Accounting
    37. Percentage
    38. Fraction
    39. Scientific
    40. Special
    41. Custom
    42. Formatting Cells Alignment
    43. Text Alignment
    44. Horizontal
    45. Vertical
    46. Text Control
    47. Wrap Text
    48. Shrink To Fit
    49. Merge Cells
    50. Right-to-left
    51. Text direction
    52. Orientation
    53. Font Name
    54. Font Style
    55. Font Size
    56. Underline
    57. Font Color
    58. Font Effects
    59. Strikethrough
    60. Subscript
    61. Superscript
    62. Border
    63. Border Index
    64. Line Style
    65. Line Thickness
    66. Line Color
    67. Pattern Style
    68. Protection
    69. Locking Cells
    70. 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.

    1. Define the cell where you want to apply the wrap text using the range property.
    2. Type a dot to see the list of the properties and methods for that cell.
    3. Select the “WrapText” property from the list.
    4. 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:

    1. xlDiagonalDown (Border running from the upper left-hand corner to the lower right of each cell in the range).
    2. xlDiagonalUp (Border running from the lower left-hand corner to the upper right of each cell in the range).
    3. xlEdgeBottom (Border at the bottom of the range).
    4. xlEdgeLeft (Border at the left-hand edge of the range).
    5. xlEdgeRight (Border at the right-hand edge of the range).
    6. xlEdgeTop (Border at the top of the range).
    7. xlInsideHorizontal (Horizontal borders for all cells in the range except borders on the outside of the range).
    8. 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:

    1. xlPatternAutomatic (Excel controls the pattern.)
    2. xlPatternChecker (Checkerboard.)
    3. xlPatternCrissCross (Criss-cross lines.)
    4. xlPatternDown (Dark diagonal lines running from the upper left to the lower right.)
    5. xlPatternGray16 (16% gray.)
    6. xlPatternGray25 (25% gray.)
    7. xlPatternGray50 (50% gray.)
    8. xlPatternGray75 (75% gray.)
    9. xlPatternGray8 (8% gray.)
    10. xlPatternGrid (Grid.)
    11. xlPatternHorizontal (Dark horizontal lines.)
    12. xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.)
    13. xlPatternLightHorizontal (Light horizontal lines.)
    14. xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.)
    15. xlPatternLightVertical (Light vertical bars.)
    16. xlPatternNone (No pattern.)
    17. xlPatternSemiGray75 (75% dark moiré.)
    18. xlPatternSolid (Solid color.)
    19. 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.

    Источник

    Like this post? Please share to your friends:
  • Wrapping lines in word
  • Wrap the text in excel
  • Wrap text word cell
  • Wrap text in excel по русски
  • Wrap text excel на русском