Addindent vba excel описание

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Range.AddIndent property (Excel)

vbaxl10.chm144075

vbaxl10.chm144075

excel

Excel.Range.AddIndent

47cfb2a4-9050-354f-08f6-e86f0164be02

05/10/2019

medium

Range.AddIndent property (Excel)

Returns or sets a Variant value that indicates if text is automatically indented when the text alignment in a cell is set to equal distribution (either horizontally or vertically).

Syntax

expression.AddIndent

expression A variable that represents a Range object.

Remarks

Set the value of this property to True to automatically indent text when the text alignment in the cell is set, either horizontally or vertically, to equal distribution.

To set text alignment to equal distribution, you can set the VerticalAlignment property to xlVAlignDistributed when the value of the Orientation property is xlVertical, and you can set the HorizontalAlignment property to xlHAlignDistributed when the value of the Orientation property is xlHorizontal.

Example

This example sets the horizontal alignment for text in cell A1 on Sheet1 to equal distribution and then indents the text.

With Worksheets("Sheet1").Range("A1") 
 .HorizontalAlignment = xlHAlignDistributed 
 .AddIndent = True 
End With

[!includeSupport and feedback]

Show All

AddIndent Property

AddIndent property as it applies to the Style object.

True if text is automatically indented when
the text alignment in a cell is set to equal distribution either horizontally or
vertically. Read/write Boolean.

expression.AddIndent

expression   Required. An expression that returns
a Style object.

AddIndent property as it applies to the CellFormat and Range objects.

True if text is automatically indented when the text alignment in a cell is set to equal distribution either horizontally or vertically. Read/write
Variant.

expression.AddIndent

expression   Required. An expression that returns one of the above objects.

Remarks

To set text alignment to equal distribution, you can set the VerticalAlignment property to xlVAlignDistributed when the value of the Orientation property is xlVertical, and you can set the HorizontalAlignment property to xlHAlignDistributed when the value of the Orientation property is xlHorizontal.

Example

This example sets the horizontal alignment for text in cell A1 on Sheet1 to equal distribution and then indents the text.

With Worksheets("Sheet1").Range("A1")
    .HorizontalAlignment = xlHAlignDistributed
    .AddIndent = True
End With

Содержание

  1. Объект Range (Excel)
  2. Примечания
  3. Пример
  4. Методы
  5. Свойства
  6. См. также
  7. Поддержка и обратная связь
  8. Свойство Application.Range (Excel)
  9. Синтаксис
  10. Параметры
  11. Замечания
  12. Пример
  13. Поддержка и обратная связь
  14. VBA Format Cells
  15. Formatting Cells
  16. AddIndent
  17. Borders
  18. FormulaHidden
  19. HorizontalAlignment
  20. VBA Coding Made Easy
  21. IndentLevel
  22. Interior
  23. Locked
  24. MergeCells
  25. NumberFormat
  26. NumberFormatLocal
  27. Orientation
  28. Parent
  29. ShrinkToFit
  30. VerticalAlignment
  31. WrapText
  32. VBA Code Examples Add-in

Объект Range (Excel)

Представляет ячейку, строку, столбец или группу ячеек, содержащую один или несколько смежных блоков ячеек или объемный диапазон.

Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.

Примечания

Элемент по умолчанию объекта Range направляет вызовы без параметров в свойство Value, а вызовы с параметрами — в элемент Item. Таким образом, someRange = someOtherRange соответствует someRange.Value = someOtherRange.Value , someRange(1) соответствует someRange.Item(1) и someRange(1,1) соответствует someRange.Item(1,1) .

В разделе Пример описаны следующие свойства и методы для возврата объекта Range:

  • Свойства Range и Cells объекта Worksheet
  • Свойства Range и Cells объекта Range
  • Свойства Rows и Columns объекта Worksheet
  • Свойства Rows и Columns объекта Range
  • Свойство Offset объекта Range
  • Метод Union объекта Application

Пример

Чтобы вернуть объект Range, представляющий одну ячейку или диапазон ячеек, используйте синтаксис Range ( arg ), где arg обозначает диапазон. В следующем примере значение ячейки A1 помещается в ячейку A5.

В следующем примере диапазон A1:H8 заполняется случайными числами путем задания формулы для каждой ячейки в диапазоне. При использовании без квалификатора объекта (объекта слева от точки) свойство Range возвращает диапазон на активном листе. Если активное окно не является листом, метод завершается с ошибкой.

Используйте метод Activate объекта Worksheet, чтобы активировать лист перед использованием свойства Range без явного квалификатора объекта.

В следующем примере очищается содержимое диапазона Criteria.

Если используется текстовый аргумент для адреса диапазона, необходимо указать адрес в нотации стиля A1 (нельзя использовать нотацию в стиле R1C1).

Чтобы получить диапазон, содержащий все отдельные ячейки листа, используйте свойство Cells на листе. Вы можете обращаться к отдельным ячейкам, используя синтаксис Item(строка, столбец), где строка — индекс строки, а столбец — индекс столбца. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range. В следующем примере на первом листе активной книги ячейке A1 присваивается значение 24, а в ячейке B1 — значение 42.

В следующем примере задается формула для ячейки A2.

Хотя также можно использовать Range(«A1») , чтобы вернуть значение ячейки A1, иногда свойство Cells может быть удобнее, так как позволяет использовать переменную для строки или столбца. В следующем примере создаются заголовки столбцов и строк на листе Sheet1. Обратите внимание, что после активации листа можно использовать свойство Cells без явного объявления листа (оно возвращает ячейку на активном листе).

Хотя для изменения ссылок в стиле A1 можно использовать строковые функции Visual Basic, проще (и лучше при программировании) использовать нотацию Cells(1, 1) .

Используйте синтаксис_выражение_.Cells, где выражение возвращает объект Range, чтобы получить диапазон с тем же адресом, состоящий из отдельных ячеек. В таком диапазоне отдельные ячейки доступны с помощью синтаксиса Item(строка, столбец) относительно левого верхнего угла первой области диапазона. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range. В следующем примере на первом листе активной книги в ячейках C5 и D5 указывается формула.

Чтобы вернуть объект Range, используйте синтаксис Range ( ячейка1, ячейка2 ), где ячейка1 и ячейка2 — это объекты Range, указывающие начальную и конечную ячейки. В следующем примере устанавливается тип линии границы для ячеек A1:J10.

Имейте в виду, что точка перед каждым появлением свойства Cells является обязательной, если результат предыдущего оператора With нужно применять к свойству Cells. В данном случае указано, что ячейки расположены на листе один (без точки свойство Cells будет возвращать ячейки активного листа).

Чтобы получить диапазон, содержащий все строки листа, используйте свойство Rows на листе. Вы можете обращаться к отдельным строкам с помощью синтаксиса Item(строка), где строка — это индекс строки. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range.

Недопустимо указывать второй параметр свойства Item для диапазонов, состоящих из строк. Сначала нужно преобразовать их в отдельные ячейки, используя свойство Cells.

В следующем примере удаляются строки 5 и 10 первого листа активной книги.

Чтобы получить диапазон, содержащий все столбцы листа, используйте свойство Columns на листе. Вы можете обращаться к отдельным столбцам с помощью синтаксиса Item(строка) [sic], где строка — это индекс столбца в виде числа или адреса столбца в формате А1. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range.

Недопустимо указывать второй параметр свойства Item для диапазонов, состоящих из столбцов. Сначала нужно преобразовать их в отдельные ячейки, используя свойство Cells.

В следующем примере удаляются столбцы B, C, E и J первого листа активной книги.

Используйте синтаксис_выражение_.Rows, где выражение возвращает объект Range, чтобы получить диапазон, состоящий из строк первой области диапазона. Вы можете обращаться к отдельным строкам с помощью синтаксиса Item(строка), где строка — это относительный индекс строки от верхнего края первой области диапазона. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range.

Недопустимо указывать второй параметр свойства Item для диапазонов, состоящих из строк. Сначала нужно преобразовать их в отдельные ячейки, используя свойство Cells.

В следующем примере удаляются диапазоны C8:D8 и C6:D6 первого листа активной книги.

Используйте синтаксис_выражение_.Columns, где выражение возвращает объект Range, чтобы получить диапазон, состоящий из столбцов первой области диапазона. Вы можете обращаться к отдельным столбцам с помощью синтаксиса Item(строка) [sic], где строка — это относительный индекс столбца от левого края первой области диапазона, указанный в виде числа или адреса столбца в формате A1. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range.

Недопустимо указывать второй параметр свойства Item для диапазонов, состоящих из столбцов. Сначала нужно преобразовать их в отдельные ячейки, используя свойство Cells.

В следующем примере удаляются диапазоны L2:L10, G2:G10, F2:F10 и D2:D10 первого листа активной книги.

Чтобы вернуть диапазон с указанным смещением относительно другого диапазона, используйте синтаксис Offset ( строка, столбец ), где строка и столбец — это смещения строк и столбцов. В следующем примере выделяются ячейки, расположенные на три строки вниз и на один столбец вправо от ячейки в левом верхнем углу текущего выделенного фрагмента. Нельзя выбрать ячейку, которая находится не на активном листе, поэтому сначала необходимо активировать лист.

Используйте синтаксис Union ( диапазон1, диапазон2, . ) для возврата диапазонов из нескольких областей, то есть диапазонов, состоящих из двух или более смежных блоков ячеек. В следующем примере создается объект, определенный как объединение диапазонов A1:B2 и C3:D4, а затем выбирается определенный диапазон.

При работе с выделенными фрагментами, содержащими несколько областей, удобно применять свойство Areas. Оно разделяет выделенный фрагмент с несколькими областями на отдельные объекты Range, а затем возвращает объекты в виде коллекции. Используйте свойство Count в возвращенной коллекции, чтобы убедиться, что выделение содержит более одной области, как показано в следующем примере.

В этом примере используется метод AdvancedFilter объекта Range для создания списка уникальных значений, а также количества появлений этих уникальных значений в диапазоне столбца A.

Методы

Свойства

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Свойство Application.Range (Excel)

Возвращает объект Range , представляющий ячейку или диапазон ячеек.

Синтаксис

expression. Диапазон (ячейка1, ячейка2)

выражение: переменная, представляющая объект Application.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Cell1 Обязательный Variant Имя диапазона. Это должна быть ссылка в стиле A1 на языке макроса. Он может содержать оператор диапазона (двоеточие), оператор пересечения (пробел) или оператор объединения (запятая). Он также может включать знаки доллара, но они игнорируются. Используйте локально определенное имя в любой части диапазона. При использовании имени предполагается, что оно записано на языке макроса.
Cell2 Необязательный Variant Ячейка в левом верхнем и правом нижнем углах диапазона. Может быть объектом Range, содержащим одну ячейку, весь столбец или всю строку, или строкой, указывающей одну ячейку на языке макроса.

Замечания

При использовании без квалификатора объекта это свойство является ярлыком для ActiveSheet.Range (оно возвращает диапазон из активного листа; если активный лист не является листом, свойство завершается ошибкой).

При применении к объекту Range это свойство выполняется относительно объекта Range. Например, если выбрана ячейка C3, свойство Selection.Range(«B1») возвращает ячейку D3, так как оно выполняется относительно объекта Range, возвращаемого свойством Selection. С другой стороны, код ActiveSheet.Range(«B1») всегда возвращает ячейку B1.

Пример

В этом примере ячейке A1 на Листе1 присваивается значение 3,14159.

В этом примере создается формула в ячейке A1 на Листе1.

В этом примере действия повторяются в ячейках A1:D10 на Листе1. Если в одной из ячеек есть значение меньше 0,001, в коде выполняется замена этого значения на 0 (ноль).

В этом примере выполняется цикл в диапазоне с именем TestRange и отображается количество пустых ячеек в диапазоне.

В этом примере для шрифта в ячейках A1:C5 на Листе1 устанавливается курсивное начертание. В примере используется синтаксис 2 свойства Range.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

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.

Источник

In this Article

  • Formatting Cells
    • AddIndent
    • Borders
    • Font
    • FormulaHidden
    • HorizontalAlignment
    • IndentLevel
    • Interior
    • Locked
    • MergeCells
    • NumberFormat
    • NumberFormatLocal
    • Orientation
    • Parent
    • ShrinkToFit
    • VerticalAlignment
    • WrapText

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:

Sub SetCellFormat()

    With Worksheets("Sheet1").Range("B5:C7")
     .HorizontalAlignment = xlHAlignDistributed
     .AddIndent = True
     .Font.FontStyle = "Italic"
     .NumberFormat = "General"
     .Interior.Color = RGB(128, 100, 250)
    End With

End Sub

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).

With Worksheets("Sheet1").Range("A1")
 .Orientation = xlVertical
 .VerticalAlignment = xlVAlignDistributed
 .AddIndent = True
End With

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:

Worksheets("Sheet1").Range("B2").BorderAround LineStyle:=xlDash, ColorIndex:=3

Font

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:

With Range("A1:C5").Font
 .Name = "Century" 
 .FontStyle = "Bold" 
 .Strikethrough = True
End With

FormulaHidden

This property returns or sets a variant value that indicates if the formula will be hidden when the worksheet is protected. For example:

 Worksheets("Sheet1").Range("A1:B1").FormulaHidden = True

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:

Worksheets("Sheet1").Range("D3").HorizontalAlignment = xlRight

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!

automacro

Learn More

IndentLevel

It returns or sets an integer value between 0 and 15 that represents the indent level for the cell or range.

Worksheets("Sheet1").Range("A1").IndentLevel = 7

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:

If Not Range("A1").Interior.ThemeColor = ThemeColorLight2 Then
   Range("A1").Interior.Pattern = xlPatternUp
End If

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.

Worksheets("Sheet1").Range("A1:B2").Locked = False 
Worksheets("Sheet1").Protect

VBA Programming | Code Generator does work for you!

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:

Worksheets("Sheet1").Range("C5:D7").MergeCells = True

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:

Range("A1").NumberFormat = "0.00E+00"
Range("B1").NumberFormat = "0.00%"

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.

Worksheets("Sheet1").Range("A1").Orientation = -60

Parent

This is a read-only property that returns the parent object of a specified object.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

ShrinkToFit

This property returns or sets a variant value that indicates if text automatically shrinks to fit in the available column width.

Worksheets("Sheet1").Range("A1").ShrinkToFit = True

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:

Worksheets("Sheet1").Range("A1").VerticalAlignment = xlTop

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:wrap text

this code below will return Null in the Immediate Window:

?Worksheets("Sheet1").Range("A1:B1").WrapText
title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Language-specific Properties, Methods, and Functions

vbaxl10.chm5278881

vbaxl10.chm5278881

excel

abf2101c-93ee-352b-6a67-478b9eb09003

06/08/2017

medium

Language-specific Properties, Methods, and Functions

The Excel Visual Basic for Applications (VBA) object model has language-specific elements for use with Asian and right-to-left languages.

The following table lists methods that have language-specific arguments. Methods that have new arguments or fewer arguments than in earlier versions of Excel are noted.

Method Objects Comments
Add Phonetics
AddLabel Shapes
AddTextbox Shapes
AutoFormat Range
CheckSpelling Application, Chart, Range, Worksheet Added SpellLang and removed IgnoreInitialAlefHamza and IgnoreFinalYaa
Find Application, Range Removed MatchControlCharacters, MatchDiacritics, MatchKashida, and MatchAlefHamza
GetPhonetic Application
Replace Range Removed MatchControlCharacters, MatchDiacritics, MatchKashida, and MatchAlefHamza
SetPhonetic Range
Sort Range Removed IgnoreControlCharacters, IgnoreDiacritics, and IgnoreKashida
SortSpecial Range

Properties that return or set language-specific attributes are listed in the following table.

Property Objects
AddIndent Range, Style
AddressLocal Range
Alignment Phonetic, Phonetics, TextEffectFormat, TickLabels
CharacterType Phonetic, Phonetics
ControlCharacters Application
CursorMovement Application
DefaultSheetDirection Application
DisplayRightToLeft Window, Worksheet
FileFormat Workbook
HorizontalAlignment AxisTitle, ChartTitle, DataLabel, DataLabels, DisplayUnitLabel, Range, Style, TextFrame
IMEMode Validation
International Application
Item Phonetics
Length Phonetics
Phonetic Range
PhoneticCharacters Characters
Phonetics Range
ReadingOrder AxisTitle, ChartTitle, DataLabel, DataLabels, DisplayUnitLabel, Range, Style, TextFrame, TickLabels
Start Phonetics
VerticalAlignment AxisTitle, ChartTitle, DataLabel, DataLabels, DisplayUnitLabels, Range, Style, TextFrame

The following are language-specific worksheet functions:

  • FindB

  • ReplaceB

  • SearchB

  • USDollar

[!includeSupport and feedback]

Понравилась статья? Поделить с друзьями:
  • Add worksheet in excel vba
  • Add workbook in excel vba
  • Add word of the day
  • Add word in video
  • Add word in excel