Interior pattern vba excel

Добавление узора (штрихового рисунка) в ячейку (диапазон) и присвоение узору цвета с помощью кода VBA Excel. Константы XlPattern и XlThemeColor.

Добавление узора в ячейку

Синтаксис добавления узора

Добавление узора в ячейку (диапазон ячеек) с цветом по умолчанию:

Range.Interior.Pattern = ConstantXlPattern

ConstantXlPattern – константа из коллекции XlPattern, задающая шаблон узора (штрихового рисунка).

Свойство Interior объекта Range возвращает объект Interior (внутренняя область диапазона), а свойство Pattern объекта Interior задает шаблон узора ячейки (диапазона) или возвращает его числовое значение.

Константы XlPattern

Шаблоны узоров (штриховых рисунков) с цветом по умолчанию:

Шаблоны узоров для ячеек

Таблица констант из коллекции XlPattern:

Константа Значение Описание
xlPatternNone -4142 Нет узора
xlPatternGray75 -4126 75% серый
xlPatternGray50 -4125 50% серый
xlPatternGray25 -4124 25% серый
xlPatternHorizontal -4128 Темные горизонтальные линии
xlPatternVertical -4166 Темные вертикальные полосы
xlPatternDown -4121 Темные диагональные линии слева вниз
xlPatternUp -4162 Темные диагональные линии слева вверх
xlPatternSolid 1 Сплошной цвет
xlPatternChecker 9 Шахматная доска
xlPatternSemiGray75 10 75% темно-серый
xlPatternLightHorizontal 11 Светлые горизонтальные линии
xlPatternLightVertical 12 Светлые вертикальные полосы
xlPatternLightDown 13 Светлые диагональные линии слева вниз
xlPatternLightUp 14 Светлые диагональные линии слева вверх
xlPatternGrid 15 Сетка
xlPatternCrissCross 16 Перекрестные линии
xlPatternGray16 17 16% серый
xlPatternGray8 18 8% серый
xlPatternAutomatic -4105 Шаблоном узора управляет Excel

Присвоение узору цвета

Присвоение одного из стандартных цветов узору в ячейке (диапазоне ячеек):

Range.Interior.PatternThemeColor = ConstantXlThemeColor

ConstantXlThemeColor – константа из коллекции XlThemeColor, задающая цвет узора (штрихового рисунка).

Константы XlThemeColor

Стандартные цвета узоров в ячейках на примере рисунка «Темные вертикальные полосы»:

Стандартные цвета узоров для ячеек

Таблица констант из коллекции XlThemeColor:

Константа Значение Описание
xlThemeColorDark1 1 Светлый 1
xlThemeColorLight1 2 Темный 1
xlThemeColorDark2 3 Светлый 2
xlThemeColorLight2 4 Темный 2
xlThemeColorAccent1 5 Акцент 1
xlThemeColorAccent2 6 Акцент 2
xlThemeColorAccent3 7 Акцент 3
xlThemeColorAccent4 8 Акцент 4
xlThemeColorAccent5 9 Акцент 5
xlThemeColorAccent6 10 Акцент 6
xlThemeColorHyperlink 11 Гиперссылка
xlThemeColorFollowedHyperlink 12 Гиперссылка при наведении

Примеры

Пример 1
Проверка наличия узора в активной ячейке:

Sub Primer1()

    If ActiveCell.Interior.Pattern = xlPatternNone Then

        MsgBox «В ячейке узора нет!»

    Else

        MsgBox «В ячейке узор есть!»

    End If

End Sub

Пример 2
В столбец «A» запишем значения констант из коллекции XlPattern, а в столбец «B» вставим соответствующие им узоры:

Sub Primer2()

Dim myArr, i

myArr = Array(4142, 4126, 4125, 4124, 4128, 4166, 4121, _

4162, 1, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 4105)

    For i = 0 To UBound(myArr)

        Cells(i + 1, 1) = CStr(myArr(i))

        Cells(i + 1, 2).Interior.Pattern = myArr(i)

    Next

End Sub

Пример 3
В столбец «A» запишем значения констант из коллекции XlThemeColor, а в столбец «B» вставим соответствующие им цвета для рисунка «Шахматная доска»:

Sub Primer3()

Dim i

    For i = 1 To 12

        Cells(i, 1) = i

        With Cells(i, 2).Interior

            .Pattern = xlPatternChecker

            .PatternThemeColor = i

        End With

    Next

End Sub

Смотрите как залить ячейку цветом (фоном).


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

Interior.Pattern property (Excel)

vbaxl10.chm551076

vbaxl10.chm551076

excel

Excel.Interior.Pattern

90587a6d-273c-00df-bb12-1a4415591705

04/27/2019

medium

Interior.Pattern property (Excel)

Returns or sets a Variant value, containing an XlPattern constant, that represents the interior pattern.

Syntax

expression.Pattern

expression A variable that represents an Interior object.

Example

This example adds a crisscross pattern to the interior of cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1"). _ 
 Interior.Pattern = xlPatternCrissCross

[!includeSupport and feedback]

Содержание

  1. VBA Excel. Узор (рисунок) в ячейке
  2. Добавление узора в ячейку
  3. Синтаксис добавления узора
  4. Константы XlPattern
  5. Присвоение узору цвета
  6. Microsoft Excel
  7. Автоматизация работы в документах Microsoft Excel
  8. Запись макросов
  9. Выполнение макросов
  10. Создание кнопки макроса на панели быстрого доступа
  11. Удаление макроса
  12. Редактирование макроса
  13. VBA Vault
  14. Cell Fills (Color, Patterns, & Gradients)
  15. What This VBA Code Does
  16. xlPattern Constants
  17. Using VBA Code Found On The Internet
  18. Getting Started Automating Excel
  19. How Do I Modify This To Fit My Specific Needs?

VBA Excel. Узор (рисунок) в ячейке

Добавление узора (штрихового рисунка) в ячейку (диапазон) и присвоение узору цвета с помощью кода VBA Excel. Константы XlPattern и XlThemeColor.

Добавление узора в ячейку

Синтаксис добавления узора

Добавление узора в ячейку (диапазон ячеек) с цветом по умолчанию:

ConstantXlPattern – константа из коллекции XlPattern, задающая шаблон узора (штрихового рисунка).

Свойство Interior объекта Range возвращает объект Interior (внутренняя область диапазона), а свойство Pattern объекта Interior задает шаблон узора ячейки (диапазона) или возвращает его числовое значение.

Константы XlPattern

Шаблоны узоров (штриховых рисунков) с цветом по умолчанию:

Таблица констант из коллекции XlPattern:

Константа Значение Описание
xlPatternNone -4142 Нет узора
xlPatternGray75 -4126 75% серый
xlPatternGray50 -4125 50% серый
xlPatternGray25 -4124 25% серый
xlPatternHorizontal -4128 Темные горизонтальные линии
xlPatternVertical -4166 Темные вертикальные полосы
xlPatternDown -4121 Темные диагональные линии слева вниз
xlPatternUp -4162 Темные диагональные линии слева вверх
xlPatternSolid 1 Сплошной цвет
xlPatternChecker 9 Шахматная доска
xlPatternSemiGray75 10 75% темно-серый
xlPatternLightHorizontal 11 Светлые горизонтальные линии
xlPatternLightVertical 12 Светлые вертикальные полосы
xlPatternLightDown 13 Светлые диагональные линии слева вниз
xlPatternLightUp 14 Светлые диагональные линии слева вверх
xlPatternGrid 15 Сетка
xlPatternCrissCross 16 Перекрестные линии
xlPatternGray16 17 16% серый
xlPatternGray8 18 8% серый
xlPatternAutomatic -4105 Шаблоном узора управляет Excel

Присвоение узору цвета

Присвоение одного из стандартных цветов узору в ячейке (диапазоне ячеек):

Источник

Microsoft Excel

трюки • приёмы • решения

Автоматизация работы в документах Microsoft Excel

Для автоматизации работы приложений часто используются макросы. Любой макрос — это последовательность действий, записанная под определенным именем. Если при работе с Microsoft Excel возникает необходимость несколько раз выполнить одну и ту же последовательность операций (например, сложное форматирование текущей ячейки или добавление новой строки с заполнением некоторых ее ячеек формулами), то можно записать эти действия, а затем воспроизводить их столько раз, сколько потребуется.

Записанный макрос можно вызывать для выполнения с помощью специального диалогового окна или при помощи комбинации клавиш. Кроме того, макрос можно назначить кнопке на панели быстрого доступа. В общем случае, для того чтобы записать макрос, не нужно быть программистом — достаточно просто знать, как выполнить команды, приводящие к нужному результату.

Вкладка Разработчик, позволяющая записывать макросы, по умолчанию скрыта. Для того чтобы ее показать, необходимо выбрать Office → Параметры Excel → Основные и использовать опцию Показывать вкладку «Разработчик» на ленте. После установки этого флажка на ленте появится вкладка Разработчик.

Запись макросов

Для того чтобы записать макрос, необходимо:

  1. Детально представить ту последовательность действий, которую нужно выполнять (во избежание возможных ошибок, лишних или неправильных действий).
  2. Выбрать элемент, к которому будут применяться действия, записываемые в макрос (установить курсор в пределах ячейки и пр.).
  3. Вызвать диалоговое окно Запись макроса одним из двух способов:
    • нажать кнопку Запись макроса на панели Код вкладки Разработчик;
    • нажать кнопку Запись макроса в левой части строки состояния Excel.
  4. Ввести в поле Имя макроса название создаваемого макроса. При этом первым символом имени макроса должна быть буква. Остальные символы могут быть как буквами, так и цифрами или знаком подчеркивания. В имени не допускаются пробелы; в качестве разделителей слов рекомендуется использовать знаки подчеркивания.
  5. В выпадающем списке Сохранить в указать, где будет сохранен данный макрос. Возможные варианты:
    • Личная книга макросов — макрос сохраняется в специальный файл, который будет доступен для всех документов сразу после загрузки Excel;
    • Новая книга — будет создана новая книга, и макрос будет сохранен в ней. Этот макрос будет доступен только в том случае, если содержащая его книга будет открыта;
    • Эта книга — макрос будет сохранен в текущей книге. Обычно такие макросы необходимы, когда их использование ограничено мелкой автоматизацией в текущей книге. Тем не менее, макрос будет доступен из других документов, если они будут открыты параллельно.
  6. Если необходимо, чтобы макрос вызывался комбинацией клавиш, ввести букву или цифру в поле Сочетание клавиш.

Если вводится буква, то важен как регистр, так и раскладка. Например, если вводится буква д (малая русская), то комбинация клавиш для этого макроса будет Ctrl+д, но не Ctrl+I (малая английская L, которая находится на той же клавише).

  • Нажать кнопку OK, затем кнопку Запись макроса на панели Код вкладки Разработчик, которая в строке состояния превратится в кнопку Остановить запись, останавливающую запись макроса.
  • Выполнить последовательность действий, которые будут записаны в макрос.

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

  • Завершить запись макроса нажатием кнопки Остановить запись. По окончании записи макроса он появляется в списке макросов иод своим именем.
  • Выполнение макросов

    Для выполнения макроса можно воспользоваться диалоговым окном Макрос. Чтобы отобразить это окно, можно нажать комбинацию клавиш Alt+F8 либо воспользоваться кнопкой Макросы на панели Код. Далее в этом окне необходимо выбрать требуемый макрос и нажать кнопку Выполнить. Второй возможностью выполнить макрос является комбинация клавиш, выбранная на этапе создания макроса. Кроме того, в Excel предусмотрена возможность вызова макроса при помощи кнопки па панели быстрого доступа.

    Создание кнопки макроса на панели быстрого доступа

    Для создания кнопки на панели быстрого доступа нужно:

    1. Вызвать диалоговое окно Параметры Excel и перейти на вкладку Настройка.
    2. В выпадающем списке Выбрать команды из выбрать пункт Макросы.
    3. Выбрать нужный макрос из списка макросов и нажать кнопку Добавить — он скопируется в правое окно и станет доступен в виде кнопки на панели быстрого доступа.
    4. Чтобы для созданной кнопки изменить рисунок и отображаемое имя, следует воспользоваться командой Изменить.
    5. Нажать кнопку ОК в диалоговом окне Параметры Excel.

    В результате кнопка добавится на панель быстрого доступа. Отображаемое имя будет появляться в виде всплывающей подсказки при наведении на кнопку указателя мыши.

    Удаление макроса

    Для удаления макроса следует нажать кнопку Макросы на панели Код или комбинацию клавиш Alt+F8 — появится диалоговое окно Макрос, содержащее список макросов, доступных в открытых книгах. В данном окне необходимо выбрать удаляемый макрос и нажать кнопку Удалить.

    При удалении макроса его кнопка в панели быстрого доступа не удаляется автоматически, поэтому ее нужно удалить вручную на вкладке Настройки диалогового окна Параметры Excel.

    Редактирование макроса

    Созданный макрос на самом деле представляет собой процедуру, записанную на языке программирования VBA. Ее легко можно увидеть в окне редактора Visual Basic Editor. Подробно о VBA и редакторе Visual Basic Editor рассказано в других наших статьях. Сейчас важно отметить то, что макрос записывается в виде обычного текста, а это значит, что при необходимости его легко можно редактировать.

    Для входа в режим редактирования макроса нужно:

    1. В диалоговом окне Макрос выбрать подлежащий редактированию макрос.
    2. Нажать кнопку Изменить — откроется окно Microsoft Visual Basic.

    Для примера создадим в текущей книге Excel простейший макрос, который должен применяться к выделенной ячейке и изменять ее форматирование (цвет фона — красный, цвет шрифта — светло-коричневый, Фон 2). Чтобы создать этот макрос, необходимо:

    1. Выделить любую ячейку на листе и ввести в нее какой-нибудь текст (чтобы можно было посмотреть на результат работы).
    2. Включить запись макроса с помощью кнопки Запись макроса в строке состояния.
    3. В диалоговом окне Запись макроса все параметры оставить выбранными по умолчанию и нажать кнопку ОК.
    4. На вкладке Главная (панель Шрифт) выбрать нужные параметры цвета.
    5. Остановить запись макроса при помощи кнопки Остановить запись в строке состояния.

    Теперь для того чтобы просмотреть код созданного макроса, необходимо вызвать редактор Visual Basic способом, описанным выше, — откроется окно кода для созданного макроса, в котором будет записан следующий код:

    // Макрос форматирования ячейки Макрос1 Sub Макрос1() ‘Макрос! Макрос With Selection.Interior .Pattern = xlSolid .PatternColorlndex = xlAutomatic .Color = 255 .TintAndShade = 0 .PatternTintAndShade = 0 End With With Selection.Font .ThemeColor = xlThemeColorDark2 .TintAndShade = 0 End With End Sub

    Чтобы при последовательном обращении к нескольким свойствам одного объекта каждый раз не указывать длинную цепочку типа Selection.Interior.Pattern = xlSolid, используется специальная конструкция языка VBA: With…End With — внутри нес имя объекта можно опустить, указывая лишь точку перед именем свойства.

    Для тех, кто знает английский язык, назначение и принцип работы команд в данном коде достаточно очевидны: для объекта Selection.Interior (т.е. для внутренней области выделенной ячейки) выполняется задание значений различным параметрам фона. Основные параметры — Pattern (способ заливки, в данном случае задан xlSolid, т.е. сплошным) и Color (Цвет). Аналогичным образом происходит изменение цвета шрифта (начиная со строки With Selection.Font).

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

    Цели полностью удалить код макроса в редакторе Visual Basic, то макрос также будет полностью удален (это аналогично действию кнопки Удалить диалогового окна Макрос).

    Для переименования макроса достаточно войти в режим его редактирования и в тексте программы исправить заголовок в строке Sub Макрос1() — новое имя автоматически заменит старое в списках макросов. Заметим, что не все замены происходят автоматически. Если с макросом были связаны графические объекты или кнопки, то необходимо сделать для них переназначения.

    Высокий уровень производства и дохода, являющийся результатом применения передовой технологии и крупных масштабов производства, приводит к тому, что на весьма значительную часть населения перестает давить бремя забот, связанных с удовлетворением элементарных физических потребностей. Ни одного голодного человека, если только он трезв, невозможно убедить в том, чтобы он истратил свой последний доллар на что-либо, кроме еды. Но человека, который хорошо питается, хорошо одет, имеет хорошие жилищные условия и хорошо обеспечен во всех остальных отношениях, можно убедить в том, чтобы он решил купить электробритву или электрическую зубную тетку. Не только цены и издержки производства, но и потребительский спрос становится объектом управления. Таков еще один важный дополнительный элемент в системе регулирования экономической среды…

    Источник

    VBA Vault

    An Excel, PowerPoint, & MS Word blog providing handy and creative VBA code snippets. These macro codes are well commented and are completely functional when copied into a module.

    Cell Fills (Color, Patterns, & Gradients)

    What This VBA Code Does

    This will give you a sample of the different types of cell fills you can have in Excel

    ‘PURPOSE: Show Various Ways to Modify Cell Fill
    ‘SOURCE: www.TheSpreadsheetGuru.com

    ‘Change Fill Color
    Range(«A1»).Interior.Color = RGB(141, 180, 227)

    ‘Add Pattern (See xlPattern constants for choices)
    Range(«B1»).Interior.Pattern = xlDown
    Range(«B1»).Interior.PatternColor = RGB(141, 180, 227)

    ‘Add Gradients
    With Range(«C1»).Interior
    .Pattern = xlPatternLinearGradient
    .Gradient.Degree = 180

    ‘Adjust Color Stops
    ‘Clear Default Color Stops
    .Gradient.ColorStops.Clear

    ‘Add A Color Stop
    With .Gradient.ColorStops.Add(0)
    .Color = RGB(255, 255, 255)
    End With

    ‘Add Another Color Stop
    With .Gradient.ColorStops.Add(1)
    .Color = RGB(141, 180, 227)
    End With
    End With

    xlPattern Constants

    Name Value Description
    xlPatternChecker 9 Checkerboard Pattern
    xlPatternCrissCross 16 Criss-Cross Line Pattern
    xlPatternDown -4121 Dark Diagonal Line Pattern ( )
    xlPatternGrid 15 Grid Pattern
    xlPatternHorizontal -4128 Horizontal Line Pattern
    xlPatternLightDown 13 Lighter Diagonal Line Pattern ( )
    xlPatternLightHorizontal 11 Lighter Horizontal Line Pattern
    xlPatternLightUp 14 Lighter Diagonal Line Pattern ( / )
    xlPatternLightVertical 12 Lighter Vertical Bar Pattern
    xlPatternNone -4142 No Pattern
    xlPatternSolid 1 Solid Color Fill
    xlPatternUp -4162 Dark Diagonal Line Pattern ( / )
    xlPatternVertical -4166 Darker Vertical Bar Pattern

    Using VBA Code Found On The Internet

    Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

    Getting Started Automating Excel

    Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

    Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

    How Do I Modify This To Fit My Specific Needs?

    Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it!

    I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

    I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

    Источник

    Various different patterns can be applied to cells in Excel. These patterns can be applied manually using the Format Cell dialog:

    Excel Cell Pattern
    This article will explain how you can apply different patterns to cells using VBA for Excel.

    Jump To:

    • Basics
    • Example 1, Set Pattern
    • Example 2, Get Pattern

    You can download the file and code related to this article here.


    Basics:

    The pattern of a cell can be changed using the xlPattern enumeration. The code below changes the pattern of cell A1 to the checker pattern:

    range("A1").Interior.Pattern = XlPattern.xlPatternChecker

    Result:

    Excel VBA, Fill Pattern Checker
    You can also change the color of the pattern using the code below:

    Range("A1").Interior.PatternColor = vbBlue

    Result:

    Excel VBA, Fill Pattern Color
    For more information about colors please see Excel VBA Colors.

    You can also get the index of the current pattern used in a cell using the code below. The code below prints the enumeration index of the pattern used in cell A1 in cell B1:

    Excel VBA, Fill Pattern Checker, Index
    You can also get the color code used in a pattern using the code below. The code below prints the color code of the color used for the pattern in cell A1 in cell C1:

    Cells(1, 3) = Range("A1").Interior.PatternColor

    Excel VBA, Fill Pattern Color Code


    Example 1, Set Pattern:

    In the example below there are a list of patterns in column A, and a list of colors in column B. By clicking these cells the fill pattern of cell C1 is updated.

    In the figure below you can see the pattern and color columns:

    Excel VBA, Color and Pattern Columns
    In the figure below the user has clicked on cell A6. The pattern in cell C1 is updated:

    Excel VBA, Colors and patterns, A6
    In the figure below the user has selected cell B3, therefore changing the color of the pattern in cell C1 to blue:

    Excel VBA, Colors and patterns, B3
    The main function for the program is a Worksheet_SelectionChange event handler. The event handler executes when the user selects a new cell:

    'executes when the user selects a new cell
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'checks if the selected cell is in column A
    If Target.Column = 1 Then
        'checks if the selected cell is between row 2 and
        'the last row in column A
        If Target.Row >= 2 And Target.Row <= 19 Then
            'adjusts the pattern of cell C1 to the selected pattern
            'in column A
            Range("C1").Interior.Pattern = Target.Interior.Pattern
        End If
        'checks if the selected cell is in column B
    ElseIf Target.Column = 2 Then
        'checks if the selected cell is between row 2 and
        'the last row in column B
        If Target.Row >= 2 And Target.Row <= 9 Then
            'changes the pattern color of cell C1
            Range("C1").Interior.PatternColor = Target.Interior.Color
        End If
    End If
    End Sub

    The If statement checks if the selected cell is in column A or column B. Column A would change the pattern while column B would only change the pattern color. Note that Target is the input parameter to the event handler Worksheet_SelectionChange. It determines the range selected by the user:

    If Target.Column = 1 Then
    ...
    ElseIf Target.Column = 2 Then
    ...
    End If

    The If statements below check if the selected cell is between the first and last row of its respective column:

    If Target.Row >= 2 And Target.Row <= 19 Then
    ...
    End If

    If Target.Row >= 2 And Target.Row <= 9 Then
    ...
    End If

    The line below changes the pattern of cell C1 to the pattern selected in column A:

    Range("C1").Interior.Pattern = Target.Interior.Pattern

    The line below changes the pattern color of cell C1 to the color selected by the user in column B:

    Range("C1").Interior.PatternColor = Target.Interior.Color


    Example 2, Get Pattern:

    In this example the user manually creates a fill pattern for cell A2. After pressing the run button the selected pattern and pattern color are printed in cells B2 and C2:

    Excel VBA, Get Pattern
    After changing the pattern in cell A2 and pressing the Run button again the values in cell B2 and C2 are updated:

    Excel VBA, Get Pattern 2
    The program uses a Button_Click event handler. The event handler executes when the user presses the Run button:

    Private Sub btnRun_Click()
    'gets the pattern index of cell A2
    Cells(2, 2) = Range("A2").Interior.Pattern
    'gets the color index of cell A2
    Cells(2, 3) = Range("A2").Interior.PatternColor
    End Sub

    The line below gets the pattern index of cell A2:

    Cells(2, 2) = Range("A2").Interior.Pattern

    The line below gets the color code of the color of the pattern in cell A2:

    Cells(2, 3) = Range("A2").Interior.PatternColor

    You can download the file and code related to this article here.

    See also:

    • Excel VBA, Cell Fill Color
    • Excel VBA, Formatting Cells and Ranges using the Macro Recorder
    • Excel VBA Colors
    • Excel VBA, Cell Fill Color

    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

    Child Objects commonly used with Chart Elements: Border Object, ChartFillFormat Object, Interior Object, Font Object

    Contents:

    Border Object

    ChartFillFormat Object

    Interior Object

    Font Object

    You can use the Border object, ChartFillFormat Object, Interior Object & Font Object with several Chart Elements to customize the border, fill, interior and font settings. Each object has multiple properties to customize it. Border object is used to manipulate a chart element’s border, the ChartFillFormat object is used to manipulate fill formatting for chart elements, the Interior object is used to manipulate the chart element’s interior (inside area), and the Font object enables you to manipulate the font attributes viz. font name, font size, font color, … for all text values.

    Border Object

    Border ObjectobjChartElement.Border — use the Border Property to return a Border object, to manipulate a chart element’s border.

    Commonly used Properties of the Border Object, with Charts:

    Property Syntax Description
    Color Property objBorder.Color sets or returns the primary color for the border — create a color value by using the RGB function

    Sheets(«Sheet1»).ChartObjects(1).Chart.Axes(xlCategory).Border.Color = RGB(0, 255, 0)
    Sheets(«Sheet1»).ChartObjects(1).Chart.Axes(xlValue).AxisTitle.Border.Color = RGB(0, 255, 0)
    Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Border.Color = vbBlue
    Sheets(«Sheet1»).ChartObjects(1).Chart.ChartArea.Border.Color = vbRed

    ColorIndex Property             objBorder.ColorIndex      sets or returns the border color, wherein an index value (in the existing color palette) or one of the XlColorIndex constants (xlColorIndexAutomatic, xlColorIndexNone) are used to specify color

    ‘set plot area’s border color to green
    Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Border.ColorIndex = 4

    ‘consider series 1 line color, for line chart:
    With Sheets(«Sheet1»).ChartObjects(1).Chart.SeriesCollection(1).Border

    If .ColorIndex = xlColorIndexAutomatic Then

    MsgBox «Automatic»
    ‘if set to automatic color, set black color for series 1 line
    .ColorIndex = 1

    Else

    MsgBox «Non-Automatic»
    ‘if NOT set to automatic color, set red color for series 1 line
    .ColorIndex = 3

    End If

    End With

    LineStyle Property objBorder.LineStyle sets or returns the line style for the border, using the values xlGray25, xlGray50, xlGray75, or xlAutomatic or using the XlLineStyle Enumeration viz. xlContinuous (value 1) — continuous line; xlDashDot (value 4) — alternate dash & dot; xlDashDotDot (value 5) — dash-dot-dot; xlDash (value -4115) — dashed line; xlDot (value -4118) — dotted line; xlLineStyleNone (value -4142) — no line. Note that the XlLineStyle constants xlDouble & xlSlantDashDot are not applicable for charts.

    ‘turn on minor gridlines for axis
    Sheets(«Sheet1»).ChartObjects(1).Chart.Axes(xlValue).HasMinorGridlines = True
    ‘set line style for minor gridlines
    Sheets(«Sheet1»).ChartObjects(1).Chart.Axes(xlValue).MinorGridlines.Border.LineStyle = xlDash

    Weight Property objBorder.Weight sets or returns the weight for the border, using the XlBorderWeight Enumeration viz. xlHairline (value 1) — hairline / thinnest; xlThin (value 2) — thin; xlMedium (value -4138) — medium; xlThick (value 4) — thick / widest.
        Sheets(«Sheet1»).ChartObjects(1).Chart.ChartArea.Border.Weight = xlThick

    ChartFillFormat Object

    ChartFillFormat Object — use the Fill PropertyobjChartElement.Fill — to return a ChartFillFormat object (valid only for charts), to manipulate fill formatting for chart elements.

    Commonly Used Properties of the ChartFillFormat Object, with Charts:

    Property Syntax Description
    BackColor Property

    objChartFillFormat.

    BackColor

    Use the BackColor property to set or return a ChartColorFormat object that represents the background fill color of a gradient or patterned fill. Use the RGB value (RGB property of ChartColorFormat object) to return the color; use the SchemeColor index value (SchemeColor property of ChartColorFormat object) in the existing color scheme to set or return the color.
    ForeColor Property

    objChartFillFormat.

    ForeColor

    Use the ForeColor property to set or return a ChartColorFormat object that represents the fill color of a solid fill or the foreground fill color of a gradient or patterned fill. Use the RGB value (RGB property of ChartColorFormat object) to return the color; use the SchemeColor index value (SchemeColor property of ChartColorFormat object) in the existing color scheme to set or return the color. To set the interior color for the plot area with a solid fill to Yellow:

    Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Fill.ForeColor.SchemeColor = 6

    GradientColorType Property

    objChartFillFormat.

    GradientColorType

    Refer same property of the the FillFormat object (in the section of ChartFormat object) for explanation.
    GradientDegree Property

    objChartFillFormat.

    GradientDegree

    — do —
    GradientStyle Property

    objChartFillFormat.

    GradientStyle

    — do —
    GradientVariant Property

    objChartFillFormat.

    GradientVariant

    — do —
    Pattern Property objChartFillFormat.Pattern — do —
    PresetGradientType Property

    objChartFillFormat.

    PresetGradientType

    — do —
    PresetTexture Property

    objChartFillFormat.

    PresetTexture

    — do —
    TextureType Property

    objChartFillFormat.

    TextureType

    — do —
    Type Property objChartFillFormat.Type — do —
    Visible Property objChartFillFormat.Visible — do —
         

    Commonly Used Methods of the ChartFillFormat Object, with Charts:

    Method Syntax Description
    OneColorGradient Method

    objChartFillFormat.

    OneColorGradient(Style, Variant, Degree)

    Refer same method of the the FillFormat object (in the section of ChartFormat object) for explanation.
    Patterned Method

    objChartFillFormat.

    Patterned(Pattern)

    — do — 
    PresetGradient Method

    objChartFillFormat.

    PresetGradient(Style, Variant, PresetGradientType)

    — do — 
    PresetTextured Method

    objChartFillFormat.

    PresetTextured(PresetTexture)

    — do — 
    Solid Method  objChartFillFormat.Solid  — do — 
    TwoColorGradient Method  

    objChartFillFormat.

    TwoColorGradient(Style, Variant) 

    — do — 
    UserTextured Method  

    objChartFillFormat.

    UserTextured(TextureFile) 

    — do — 
    UserPicture Method 

    objChartFillFormat.UserPicture

    (PictureFile, PictureFormat, PictureStackUnit, PicturePlacement) 

    Sets an image to the specified fill. All arguments are optional. The PictureFile argument is a string value specifying the picture file name. The PictureFormat argument specifies picture display format on a column, bar picture chart, or legend key, per constants defined in XlChartPictureType EnumerationxlStack (value 2, picture is sized to repeat a maximum of 15 times in the longest stacked bar), xlStackScale (value 3, picture is sized to a specified number of units & repeated the length of the bar), xlStretch (value 1, picture is stretched the full length of the stacked bar). The PictureStackUnit argument specifies the stack or scale unit for the picture (ie. n units per picture) — a double value depending on the PictureFormat argument. The PicturePlacement argument specifies the placement of a user-selected picture on a bar in a 3-D bar or column as per values defined in the XlChartPicturePlacement EnumerationxlSides (value 1, display on sides), xlEnd (value 2, display on end), xlEndSides (value 3, display on end & sides), xlFront (value 4, display on front), xlFrontSides (value 5, display on front & sides), xlFrontEnd (value 6, display on front & end), xlAllFaces (value 7, display on all faces). 

    VBA Codes illustrating ChartFillFormat Object’s Properties & Methods:

    With Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Fill

    ‘remove fill color from Plot Area

    .Visible = msoFalse

    ‘add fill color to Plot Area

    .Visible = msoTrue

    ‘set a solid fill of uniform color — note that this is the Default & excluding this will not matter (use the Solid method to convert a gradient, textured, patterned or background fill back to a solid fill)

    .Solid

    set the interior color for the plot area to Yellow

    .ForeColor.SchemeColor = 6

    ‘returns 65535 (ForeColor.RGB is read only)

    MsgBox .ForeColor.RGB

    End With

    With Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Fill

    ‘set a one-color gradient for the Plot Area Fill, gradient fill style of msoGradientDiagonalUp, gradient variant of 2 & gradient degree of 0.9 (1 is lightest)

    .OneColorGradient msoGradientDiagonalUp, 2, 0.9

    ‘set the interior color for the plot area to Green — for gradient stop #1 (ForeColor)

    .ForeColor.SchemeColor = 4

    ‘returns 1 indicating msoGradientOneColor (ie. one-color gradient)

    MsgBox .GradientColorType

    ‘returns 3 indicating msoGradientDiagonalUp (ie. diagonal gradient moving from a bottom corner up to the opposite corner)

    MsgBox .GradientStyle

    ‘returns 2

    MsgBox .GradientVariant

    ‘returns 0.9

    MsgBox .GradientDegree

    End With

    With Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Fill

    ‘set a two-color gradient for the Plot Area Fill, gradient fill style of msoGradientHorizontal and gradient variant of 1

    .TwoColorGradient msoGradientHorizontal, 1

    ‘set the interior color for stop #1 (ForeColor) to Yellow

    .ForeColor.SchemeColor = 6

    ‘set the color for stop #2 (BackColor) to Green

    .BackColor.SchemeColor = 4

    ‘returns 2 indicating msoGradientTwoColors (ie. two-color gradient)

    MsgBox .GradientColorType

    End With

    With Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Fill

    ‘specify fill pattern for Plot Area to msoPattern90Percent (90% of the foreground color)

    .Patterned msoPattern90Percent

    ‘set fore color for the plot area to Yellow

    .ForeColor.SchemeColor = 6

    ‘set back color for the plot area to Green

    .BackColor.SchemeColor = 4

    ‘returns the fill pattern, value 12, corresponding to msoPattern90Percent

    MsgBox .Pattern

    ‘get the fill type — returns value 2 representing a Patterned fill (msoFillPatterned)

    MsgBox .Type

    End With

    With Sheets(«Sheet1»).ChartObjects(1).Chart.ChartArea.Fill

    ‘specify fill preset texture for Chart Area to msoTextureWhiteMarble — White marble texture

    .PresetTextured msoTextureWhiteMarble

    ‘returns 4 indicating msoFillTextured (ie. Textured fill)

    MsgBox .Type

    End With

    ‘set small tiles of an image to the specified fill

    Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Fill.UserTextured «C:UsersAmit TandonDocumentsPhotosIMG_2032.JPG»

    ‘using the UserPicture Method to set an image to the specified fill ie. to plot area

    Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Fill.UserPicture «C:UsersAmit TandonDocumentsPhotosIMG_2032.JPG»

    ‘using the UserPicture Method to stack (ie. repeat) pictures in a column/bar chart’s Series 1:

    Sheets(«Sheet1″).ChartObjects(1).Chart.SeriesCollection(1).Fill.UserPicture PictureFile:=»C:UsersAmit TandonDocumentsPhotosIMG_2032.JPG», PictureFormat:=xlStack

    ‘scales to 1000 units (Series 1 value) per picture ie. a value, in Series 1, of 5000 units will show 5 pictures — refer Image 1

    Sheets(«Sheet1″).ChartObjects(1).Chart.SeriesCollection(1).Fill.UserPicture PictureFile:=»C:UsersAmit TandonDocumentsPhotosDollar.jpg«, PictureFormat:=xlStackScale, PictureStackUnit:=1000

    ‘using the UserPicture Method wherein picture is stretched to full length

    Sheets(«Sheet1″).ChartObjects(1).Chart.PlotArea.Fill.UserPicture PictureFile:=»C:UsersAmit TandonDocumentsPhotosIMG_2032.JPG«, PictureFormat:=xlStretch

    With Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Fill

    ‘set plot area fill to a preset gradient — specifies gradient style as msoGradientFromCenter (Gradient running from the center out to the corners), gradient variant of 1 & preset gradient Type as msoGradientOcean

    .PresetGradient msoGradientFromCenter, 1, msoGradientOcean

    ‘returns 7 indicating msoGradientOcean (ie. Ocean gradient)

    MsgBox .PresetGradientType

    End With

    Interior Object

    Interior ObjectobjChartElement.Interior — use the Interior property to return the Interior object, to manipulate the chart element’s interior (inside area).

    Commonly Used Properties of the Interior Object, with Charts:

    Property Syntax Description
    Color Property objInterior.Color sets or returns the primary color of the interior, and create a color value by using the RGB function.
    ColorIndex Property objInterior.ColorIndex sets or returns the interior color, as an index value (in the existing color palette) or one of the XlColorIndex constants (xlColorIndexAutomatic, xlColorIndexNone).
    Pattern Property objInterior.Pattern sets or returns the interior pattern, as per constants / values defined in XlPattern EnumerationxlPatternSolid (value 1 — solid color); xlPatternChecker (value 9, checkerboard); xlPatternLightHorizontal (value 11, light horizontal lines); xlPatternLightVertical (value 12, light vertical bars); xlPatternLightDown (value 13, Light diagonal lines running from the upper left to the lower right); xlPatternGrid (value 15 — Grid); xlPatternGray16 (value 17, 16% gray); xlPatternAutomatic (value -4105, Excel controls pattern); xlPatternHorizontal (value -4128, Dark horizontal lines); and so on.
    PatternColor Property objInterior.PatternColor sets or returns the color of the interior pattern, as an RGB value.
    PatternColorIndex Property objInterior.PatternColorIndex sets or returns the color of the interior pattern, as an index value (in the existing color palette) or one of the XlColorIndex constants (xlColorIndexAutomatic, xlColorIndexNone) wherein xlColorIndexNone equates with xlPatternNone of Pattern Property which indicates no pattern.

    VBA Codes illustrating Interior Object’s Properties:

    With Sheets(«Sheet1»).ChartObjects(1).Chart

    ‘set interior color of plot area to yellow

    .PlotArea.Interior.Color = vbYellow

    ‘set interior color of chart area to green

    .ChartArea.Interior.ColorIndex = 4

    End With

    With Sheets(«Sheet1»).ChartObjects(1).Chart.PlotArea.Interior

    ‘set pattern of xlLightDown indicating light diagonal lines running from the upper left to the lower right (value 13)

    .Pattern = xlLightDown

    ‘set the color of the interior pattern as an RGB value, to yellow

    .PatternColor = RGB(255, 255, 0)

    ‘returns 6, indicating color index of the interior pattern as yellow

    MsgBox .PatternColorIndex

    End With

    Font Object

    Font ObjectobjChartElement.Font — use the Font Property to return a Font object, to manipulate the font attributes viz. font name, font size, font color, …

    Commonly used Properties of the Font Object, with Charts:

    Property Syntax Description
    Background Property objFont.Background sets (or returns) background type for text in a chart, as per constants defined in XlBackground Enumeration: xlBackgroundAutomatic (value -4105) — Excel controls the background, xlBackgroundTransparent (value 2) — Transparent background, xlBackgroundOpaque (value 3) — Opaque background.
    Bold Property  objFont.Bold  sets (or returns) a bold font — True sets the font to bold 
    Color Property  objFont.Color  sets or returns the primary color for the font, and create a color value by using the RGB function.
    ColorIndex Property  objFont.ColorIndex  sets or returns the font color, as an index value (in the existing color palette) or one of the XlColorIndex constants (xlColorIndexAutomatic, xlColorIndexNone
    FontStyle Property  objFont.FontStyle  sets or returns the font style, using a string value viz. Regular, Bold, Italic, Bold Italic
    Italic Property  objFont.Italic  sets (or returns) an italic font, using a Boolean value — True sets the font to italic 
    Name Property  objFont.Name  sets or returns the font name, using a string value viz. Arial, Calibri, Times New Roman, … 
    Size Property  objFont.Size  sets or returns the font size, in points 
    Strikethrough Property  objFont.Strikethrough  sets (or returns) a font struck through with a horizontal line, using a Boolean value — True sets the font to strikethrough 
    Subscript Property  objFont.Subscript  sets (or returns) a font format as subscript — True formats the font to subscript 
    Superscript Property  objFont.Superscript  sets (or returns) a font format as superscript — True formats the font to superscript 
    Underline Property  objFont.Underline  sets or returns the type of underline for the font, using one of the XlUnderlineStyle constants: xlUnderlineStyleNone, xlUnderlineStyleSingle, xlUnderlineStyleDouble, xlUnderlineStyleSingleAccounting, xlUnderlineStyleDoubleAccounting

    VBA Codes illustrating Font Object’s Properties:

    With Sheets(«Sheet10»).ChartObjects(1).Chart

    .ChartTitle.Text = «Qtrly Sales & Profit«

    ‘set to False, so that the Chart Title font remains the same size whenever the Chart size changes

    .ChartTitle.AutoScaleFont = False

    With .ChartTitle.Font

    .Name = «Arial«

    .FontStyle = «Bold«

    .Size = 16

    .Color = RGB(255, 0, 0)

    .Strikethrough = False

    .Superscript = False

    .Subscript = False

    .Shadow = False

    .Underline = xlUnderlineStyleDouble

    End With

    With .Axes(xlCategory, xlPrimary).AxisTitle

    .Caption = «Yr-Qtr«

    .Font.Name = «Calibri«

    .Font.Bold = True

    .Font.Italic = False

    .Font.Size = 10

    .Font.ColorIndex = 5

    .Font.Underline = xlUnderlineStyleNone

    .Font.Background = xlAutomatic

    ‘format characters within a text string — starting at 4th character & a length of 3 characters — representing the word «Qtr»

    .Characters(4, 3).Font.Italic = True

    End With

    End With

    What This VBA Code Does

    This will give you a sample of the different types of cell fills you can have in Excel

    Using VBA Code Found On The Internet

    Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

    Getting Started Automating Excel

    Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

    Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

    How Do I Modify This To Fit My Specific Needs?

    Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

    I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

    I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

    Chris
    Founder, TheSpreadsheetGuru.com

    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

    Понравилась статья? Поделить с друзьями:
  • Invoice templates for word
  • Interior design by one word
  • Invoice template free for excel
  • Interior color excel vba colors
  • Invoice on word document