title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Range.IndentLevel property (Excel) |
vbaxl10.chm144147 |
vbaxl10.chm144147 |
excel |
Excel.Range.IndentLevel |
f4d5af31-904a-27eb-fb2d-e5ae38a7ebb9 |
05/11/2019 |
medium |
Range.IndentLevel property (Excel)
Returns or sets a Variant value that represents the indent level for the cell or range. Can be an integer from 0 to 15.
Syntax
expression.IndentLevel
expression A variable that represents a Range object.
Remarks
Using this property to set the indent level to a number less than 0 (zero) or greater than 15 causes an error.
Example
This example increases the indent level to 15 in cell A10.
With Range("A10") .IndentLevel = 15 End With
[!includeSupport and feedback]
Содержание
- How to Easily Return the Indentation of an Excel Cell!
- Problem: Returning the indentation of a cell
- Solution 1: Returning the indentation with an easy VBA code
- Solution 2: Professor Excel Tools
- 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
- VBA Excel. Свойства ячейки (объекта Range)
- Ячейка и объект Range
- Свойства ячейки (объекта Range)
- Простые примеры для начинающих
- Форматирование ячеек
- Name already in use
- VBA-Docs / api / Excel.Range(object).md
How to Easily Return the Indentation of an Excel Cell!
Sometimes, you receive data which is organized by indentations. For example in an Excel table, the Total has no indentation whereas all single values are indented. This could be (typically…) the case for tables provided by some controlling tools. How to deal with that? What do you do if you want to sum up all values with the indentation level 1?
Problem: Returning the indentation of a cell
Let’s assume, we have the following table (usually these tables are longer and more complicated…):
One way to evaluate the cost data is to manually type the formula as in B6: “=SUM(B3:B5)”. But for the sum in row 12, you’d have to be careful not to sum up Cost 5.1 and Cost 5.2 twice.
Therefore, the indentation levels are useful.
Solution 1: Returning the indentation with an easy VBA code
There are basically two possible solutions. The first solution is using VBA. The function is quite straight forward:
Copy and paste this code into a new VBA module. Therefore (as usual) go to the Developer ribbon. Then click on Editor, right click on Microsoft Excel Objects. Insert a new module. Paste the code into this module.
Next, you just have to type the formula =PROFEXIndentLevel. For example in cell C3:
In this example you’ll get 2 as the return.
Please note that if you use this formula on a large amount of cells it can slow down your workbooks performance.
If you don’t feel comfortable using a VBA macro, you can go with the second solution:
As the problem of getting the indentation level arises more often than expected, we included it in our Excel add-in ‘Professor Excel Tools’. You can download the free trial version with the link below. Just download it, activate it within Excel (the simple steps will be described after you click the download button) and type this formula:
Let’s say you want to get the indent level of cell A1, just type =PROFEXIndentLevel(A1). Press F9 for refreshing.
This function is included in our Excel Add-In ‘Professor Excel Tools’
(No sign-up, download starts directly)
More than 35,000 users can’t be wrong.
Источник
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.
Источник
VBA Excel. Свойства ячейки (объекта Range)
Свойства ячейки, часто используемые в коде VBA Excel. Демонстрация свойств ячейки, как структурной единицы объекта Range, на простых примерах.
Ячейка и объект Range
Объект Range в VBA Excel представляет диапазон ячеек. Он (объект Range) может описывать любой диапазон, начиная от одной ячейки и заканчивая сразу всеми ячейками рабочего листа.
- Одна ячейка – Range(«A1») .
- Девять ячеек – Range(«A1:С3») .
- Весь рабочий лист в Excel 2016 – Range(«1:1048576») .
В VBA Excel есть свойство Cells объекта Range, которое позволяет обратиться к одной ячейке в указанном диапазоне (возвращает объект Range в виде одной ячейки). Если в коде используется свойство Cells без указания диапазона, значит оно относится ко всему диапазону активного рабочего листа.
Примеры обращения к одной ячейке:
- Cells(1000) , где 1000 – порядковый номер ячейки на рабочем листе, возвращает ячейку «ALL1».
- Cells(50, 20) , где 50 – номер строки рабочего листа, а 20 – номер столбца, возвращает ячейку «T50».
- Range(«A1:C3»).Cells(6) , где «A1:C3» – заданный диапазон, а 6 – порядковый номер ячейки в этом диапазоне, возвращает ячейку «C2».
Подробнее о том, как обратиться к ячейке, смотрите в статье: Ячейки (обращение, запись, чтение, очистка).
В этой статье мы рассмотрим свойства объекта Range, применимые, в том числе, к диапазону, состоящему из одной ячейки.
Еще надо добавить, что свойства и методы объектов отделяются от объектов точкой, как в третьем примере обращения к одной ячейке: Range(«A1:C3»).Cells(6) .
Свойства ячейки (объекта Range)
Свойство | Описание |
---|---|
Address | Возвращает адрес ячейки (диапазона). |
Borders | Возвращает коллекцию Borders, представляющую границы ячейки (диапазона). Подробнее… |
Cells | Возвращает объект Range, представляющий коллекцию всех ячеек заданного диапазона. Указав номер строки и номер столбца или порядковый номер ячейки в диапазоне, мы получаем конкретную ячейку. Подробнее… |
Characters | Возвращает подстроку в размере указанного количества символов из текста, содержащегося в ячейке. Подробнее… |
Column | Возвращает номер столбца ячейки (первого столбца диапазона). Подробнее… |
ColumnWidth | Возвращает или задает ширину ячейки в пунктах (ширину всех столбцов в указанном диапазоне). |
Comment | Возвращает комментарий, связанный с ячейкой (с левой верхней ячейкой диапазона). |
CurrentRegion | Возвращает прямоугольный диапазон, ограниченный пустыми строками и столбцами. Очень полезное свойство для возвращения рабочей таблицы, а также определения номера последней заполненной строки. |
EntireColumn | Возвращает весь столбец (столбцы), в котором содержится ячейка (диапазон). Диапазон может содержаться и в одном столбце, например, Range(«A1:A20») . |
EntireRow | Возвращает всю строку (строки), в которой содержится ячейка (диапазон). Диапазон может содержаться и в одной строке, например, Range(«A2:H2») . |
Font | Возвращает объект Font, представляющий шрифт указанного объекта. Подробнее о цвете шрифта… |
HorizontalAlignment | Возвращает или задает значение горизонтального выравнивания содержимого ячейки (диапазона). Подробнее… |
Interior | Возвращает объект Interior, представляющий внутреннюю область ячейки (диапазона). Применяется, главным образом, для возвращения или назначения цвета заливки (фона) ячейки (диапазона). Подробнее… |
Name | Возвращает или задает имя ячейки (диапазона). |
NumberFormat | Возвращает или задает код числового формата для ячейки (диапазона). Примеры кодов числовых форматов можно посмотреть, открыв для любой ячейки на рабочем листе Excel диалоговое окно «Формат ячеек», на вкладке «(все форматы)». Свойство NumberFormat диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковый числовой формат. Если нужно присвоить ячейке текстовый формат, записывается так: Range(«A1»).NumberFormat = «@» . Общий формат: Range(«A1»).NumberFormat = «General» . |
Offset | Возвращает объект Range, смещенный относительно первоначального диапазона на указанное количество строк и столбцов. Подробнее… |
Resize | Изменяет размер первоначального диапазона до указанного количества строк и столбцов. Строки добавляются или удаляются снизу, столбцы – справа. Подробнее… |
Row | Возвращает номер строки ячейки (первой строки диапазона). Подробнее… |
RowHeight | Возвращает или задает высоту ячейки в пунктах (высоту всех строк в указанном диапазоне). |
Text | Возвращает форматированный текст, содержащийся в ячейке. Свойство Text диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковое содержимое и один формат. Предназначено только для чтения. Подробнее… |
Value | Возвращает или задает значение ячейки, в том числе с отображением значений в формате Currency и Date. Тип данных Variant. Value является свойством ячейки по умолчанию, поэтому в коде его можно не указывать. |
Value2 | Возвращает или задает значение ячейки. Тип данных Variant. Значения в формате Currency и Date будут отображены в виде чисел с типом данных Double. |
VerticalAlignment | Возвращает или задает значение вертикального выравнивания содержимого ячейки (диапазона). Подробнее… |
В таблице представлены не все свойства объекта Range. С полным списком вы можете ознакомиться не сайте разработчика.
Простые примеры для начинающих
Вы можете скопировать примеры кода VBA Excel в стандартный модуль и запустить их на выполнение. Как создать стандартный модуль и запустить процедуру на выполнение, смотрите в статье VBA Excel. Начинаем программировать с нуля.
Учтите, что в одном программном модуле у всех процедур должны быть разные имена. Если вы уже копировали в модуль подпрограммы с именами Primer1, Primer2 и т.д., удалите их или создайте еще один стандартный модуль.
Форматирование ячеек
Заливка ячейки фоном, изменение высоты строки, запись в ячейки текста, автоподбор ширины столбца, выравнивание текста в ячейке и выделение его цветом, добавление границ к ячейкам, очистка содержимого и форматирования ячеек.
Если вы запустите эту процедуру, информационное окно MsgBox будет прерывать выполнение программы и сообщать о том, что произойдет дальше, после его закрытия.
Источник
Name already in use
VBA-Docs / api / Excel.Range(object).md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
Range object (Excel)
Represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3D range.
The default member of Range forwards calls without parameters to the Value property and calls with parameters to the Item member. Accordingly, someRange = someOtherRange is equivalent to someRange.Value = someOtherRange.Value , someRange(1) to someRange.Item(1) and someRange(1,1) to someRange.Item(1,1) .
The following properties and methods for returning a Range object are described in the Example section:
- Range and Cells properties of the Worksheet object
- Range and Cells properties of the Range object
- Rows and Columns properties of the Worksheet object
- Rows and Columns properties of the Range object
- Offset property of the Range object
- Union method of the Application object
Use Range (arg), where arg names the range, to return a Range object that represents a single cell or a range of cells. The following example places the value of cell A1 in cell A5.
The following example fills the range A1:H8 with random numbers by setting the formula for each cell in the range. When it’s used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet. If the active sheet isn’t a worksheet, the method fails.
Use the Activate method of the Worksheet object to activate a worksheet before you use the Range property without an explicit object qualifier.
The following example clears the contents of the range named Criteria.
[!NOTE] If you use a text argument for the range address, you must specify the address in A1-style notation (you cannot use R1C1-style notation).
Use Cells on a worksheet to obtain a range consisting all single cells on the worksheet. You can access single cells via Item(row, column), where row is the row index and column is the column index. Item can be omitted since the call is forwarded to it by the default member of Range. The following example sets the value of cell A1 to 24 and of cell B1 to 42 on the first sheet of the active workbook.
The following example sets the formula for cell A2.
Although you can also use Range(«A1») to return cell A1, there may be times when the Cells property is more convenient because you can use a variable for the row or column. The following example creates column and row headings on Sheet1. Be aware that after the worksheet has been activated, the Cells property can be used without an explicit sheet declaration (it returns a cell on the active sheet).
[!NOTE] Although you could use Visual Basic string functions to alter A1-style references, it is easier (and better programming practice) to use the Cells(1, 1) notation.
Use_expression_.Cells, where expression is an expression that returns a Range object, to obtain a range with the same address consisting of single cells. On such a range, you access single cells via Item(row, column), where are relative to the upper-left corner of the first area of the range. Item can be omitted since the call is forwarded to it by the default member of Range. The following example sets the formula for cell C5 and D5 of the first sheet of the active workbook.
Use Range (cell1, cell2), where cell1 and cell2 are Range objects that specify the start and end cells, to return a Range object. The following example sets the border line style for cells A1:J10.
[!NOTE] Be aware that the period in front of each occurrence of the Cells property is required if the result of the preceding With statement is to be applied to the Cells property. In this case, it indicates that the cells are on worksheet one (without the period, the Cells property would return cells on the active sheet).
Use Rows on a worksheet to obtain a range consisting all rows on the worksheet. You can access single rows via Item(row), where row is the row index. Item can be omitted since the call is forwarded to it by the default member of Range.
[!NOTE] It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.
The following example deletes row 5 and 10 of the first sheet of the active workbook.
Use Columns on a worksheet to obtain a range consisting all columns on the worksheet. You can access single columns via Item(row) [sic], where row is the column index given as a number or as an A1-style column address. Item can be omitted since the call is forwarded to it by the default member of Range.
[!NOTE] It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.
The following example deletes column «B», «C», «E», and «J» of the first sheet of the active workbook.
Use_expression_.Rows, where expression is an expression that returns a Range object, to obtain a range consisting of the rows in the first area of the range. You can access single rows via Item(row), where row is the relative row index from the top of the first area of the range. Item can be omitted since the call is forwarded to it by the default member of Range.
[!NOTE] It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.
The following example deletes the ranges C8:D8 and C6:D6 of the first sheet of the active workbook.
Use_expression_.Columns, where expression is an expression that returns a Range object, to obtain a range consisting of the columns in the first area of the range. You can access single columns via Item(row) [sic], where row is the relative column index from the left of the first area of the range given as a number or as an A1-style column address. Item can be omitted since the call is forwarded to it by the default member of Range.
[!NOTE] It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.
The following example deletes the ranges L2:L10, G2:G10, F2:F10 and D2:D10 of the first sheet of the active workbook.
Use Offset (row, column), where row and column are the row and column offsets, to return a range at a specified offset to another range. The following example selects the cell three rows down from and one column to the right of the cell in the upper-left corner of the current selection. You cannot select a cell that is not on the active sheet, so you must first activate the worksheet.
Use Union (range1, range2, . ) to return multiple-area ranges—that is, ranges composed of two or more contiguous blocks of cells. The following example creates an object defined as the union of ranges A1:B2 and C3:D4, and then selects the defined range.
If you work with selections that contain more than one area, the Areas property is useful. It divides a multiple-area selection into individual Range objects and then returns the objects as a collection. Use the Count property on the returned collection to verify a selection that contains more than one area, as shown in the following example.
This example uses the AdvancedFilter method of the Range object to create a list of the unique values, and the number of times those unique values occur, in the range of column A.
Источник
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!
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:
this code below will return Null in the Immediate Window:
?Worksheets("Sheet1").Range("A1:B1").WrapText
Show All
IndentLevel Property
IndentLevel property as it applies to the Style object.
Returns or sets the indent level for the style.
Read/write Long.
expression.IndentLevel
expression Required. An expression that returns
a Style object.
IndentLevel property as it applies to the CellFormat and Range objects.
Returns or sets the indent level for the cell or range. Can be an integer from 0 to 15. Read/write Variant.
expression.IndentLevel
expression Required. An expression that returns one of the above objects.
Remarks
Using this property to set the indent level to a number less than 0 (zero) or greater than 15 causes an error.
Example
As it applies to the CellFormat and Range objects.
This example increases the indent level to 15 in cell A10.
With Range("A10")
.IndentLevel = 15
End With
ТРЕНИНГИ
Быстрый старт
Расширенный Excel
Мастер Формул
Прогнозирование
Визуализация
Макросы на VBA
КНИГИ
Готовые решения
Мастер Формул
Скульптор данных
ВИДЕОУРОКИ
Бизнес-анализ
Выпадающие списки
Даты и время
Диаграммы
Диапазоны
Дубликаты
Защита данных
Интернет, email
Книги, листы
Макросы
Сводные таблицы
Текст
Форматирование
Функции
Всякое
Коротко
Подробно
Версии
Вопрос-Ответ
Скачать
Купить
ПРОЕКТЫ
ОНЛАЙН-КУРСЫ
ФОРУМ
Excel
Работа
PLEX
© Николай Павлов, Planetaexcel, 2006-2022
info@planetaexcel.ru
Использование любых материалов сайта допускается строго с указанием прямой ссылки на источник, упоминанием названия сайта, имени автора и неизменности исходного текста и иллюстраций.
Техническая поддержка сайта
ООО «Планета Эксел» ИНН 7735603520 ОГРН 1147746834949 |
ИП Павлов Николай Владимирович ИНН 633015842586 ОГРНИП 310633031600071 |
The IndentLevel property returns or sets the left indent for each cell in the range and can be any integer between 0 and 15. All other settings cause an error. Presumably, indents are useful for aligning the contents of cells or for formatting text.
For instance, to set the indent level of cell A1 to 10, we can write:
Range(«A1»).IndentLevel = 10
Unfortunately, the documentation does not specify how big an indent unit is, but we can still use indent units in a relative way. Presumably, an indent level of 2 is twice that of an indent level of 1.
An alternative is to use the InsertIndent method, with the syntax:
RangeObject.InsertIndent(InsertAmount)
where InsertAmount is an integer between 0 and 15. However, in this case, the InsertAmount parameter specifies the amount to change the current indent for the range.
Continue reading here: Parse Method
Was this article helpful?
Excel VBA, Horizontal Alignment
In this article I will explain the different horizontal alignment formattings applicable to cells and range. I have also provided the VBA code required to apply them.
For examples using horizontal alignment in VBA code please see:
- Excel VBA, Set Horizontal Alignment, (Sample Code)
- Excel VBA, Get Horizontal Alignment (Sample Code)
Jump To:
- Left (Indent), xlLeft
- Center, xlCenter
- Right (Indent), xlRight
- Fill, xlFill
- Justify, xlJustify
- Center Across Selection, xlCenterAcrossSelection
- Distributed (Indent), xlDistributed
- General, xlGeneral
- Indent, IndentLevel
–
Left (Indent), xlLeft:
The following code will left align the text in cell “A1”:
Range("A1").HorizontalAlignment = xlLeft
Result:
–
Center, xlCenter:
The following code will apply the horizontal center alignment to the text in cell “A1”:
Range("A1").HorizontalAlignment = xlCenter
Result:
–
Right (Indent), xlRight:
The following code will right align the text in cell “A1”:
Range("A1").HorizontalAlignment = xlRight
Result:
–
Fill, xlFill:
The following code will fill the cell in “A1” with the text in it:
Range("A1").HorizontalAlignment = xlFill
Result:
–
Justify, xlJustify:
The following code will apply the horizontal justify formatting to the text in cell “A1”. Note that the justify property will only be apparent when you have multiple lines of text in a cell and the wrap property is on:
Range("A1").HorizontalAlignment = xlJustify
Result:
–
Center Across Selection, xlCenterAcrossSelection:
The following code centers the text in cell “A1” among the cells A1~I1. This is a good way of centering a text over multiple columns without merging the cells:
Range("A1:M1").Select
Selection.HorizontalAlignment = xlCenterAcrossSelection
Before:
After:
–
Distributed, xlDistributed:
The following command applies the distributed (indent) formatting to cell “A1”. This formatting creates spaces between the words so that the entire horizontal spacing in that cell is filled:
Range("A1").HorizontalAlignment = xlDistributed
Before:
After:
–
General, xlGeneral:
The following command applies the general horizontal formatting to cell “A1”. This formatting causes text to be left aligned and numbers to be right aligned:
Range("A1").HorizontalAlignment = xlGeneral
Result:
–
Indent, IndentLevel:
The 3 formattings left aligned, right aligned and distributed accept an indentation level. The code below applies an indentation to the cells A1, A2 and A3:
Range("A1").IndentLevel= 1
Before:
After:
See also:
- Excel VBA Formatting Cells and Ranges Using the Macro Recorder
- VBA Excel, Alignment
- Excel VBA, Set Horizontal Alignment, (Sample Code)
- Excel VBA, Get Horizontal Alignment (Sample Code)
If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com