Vba excel оформление ячеек

Программное создание границ ячеек произвольного диапазона с помощью кода VBA Excel. Свойство Borders объекта Range. Создание границ одной ячейки. Код макроса.

Программное создание границ ячеек

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

‘Для этого необходима всего одна строка:

Range(«A1:G7»).Borders.LineStyle = True

‘Вместо ключевого слова True можно

‘использовать константу xlContinuous:

Range(«A1:G7»).Borders.LineStyle = xlContinuous

‘Кроме того, для создания границ ячеек можно

‘использовать единственную строку с указанием

‘какого-нибудь параметра, например,

‘для создания сетки из синих границ:

Range(«A1:G7»).Borders.Color = vbBlue

‘или для создания сетки из границ в виде двойных линий:

Range(«A1:G7»).Borders.LineStyle = xlDouble

‘Чтобы применить при создании границ два

‘параметра, придется использовать уже две

‘строки кода, например, для создания сетки

‘из границ в виде жирных красных линий:

Range(«A1:G7»).Borders.Weight = xlThick

Range(«A1:G7»).Borders.Color = vbRed

‘Удалить границы можно с помощью строки:

Range(«A1:G7»).Borders.LineStyle = False

‘Вместо ключевого слова False можно

‘использовать константу xlNone:

Range(«A1:G7»).Borders.LineStyle = xlNone

Создание границ одной ячейки

Создать границы ячейки (только для одной ячейки) в VBA Excel можно следующим образом:

Range(«A5»).Borders.LineStyle = True

Cells(2, 8).Borders.Color = vbBlue

ActiveCell.Borders.LineStyle = xlDouble

‘Удаление границ:

ActiveCell.Borders.LineStyle = False

Пример кода записанного макроса

Запись макроса: включаем запись, выбираем диапазон «A1:E9», на панели инструментов выбираем значок «Все границы», останавливаем запись. И это все наши выполненные действия, а в результате получаем следующий код:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

Sub Макрос1()

    Range(«A1:E9»).Select

‘Отображается левая граница диапазона

    With Selection.Borders(xlEdgeLeft)

        .LineStyle = xlContinuous

        .ColorIndex = 0

        .TintAndShade = 0

        .Weight = xlThin

    End With

‘Отображается верхняя граница диапазона

    With Selection.Borders(xlEdgeTop)

        .LineStyle = xlContinuous

        .ColorIndex = 0

        .TintAndShade = 0

        .Weight = xlThin

    End With

‘Отображается нижняя граница диапазона

    With Selection.Borders(xlEdgeBottom)

        .LineStyle = xlContinuous

        .ColorIndex = 0

        .TintAndShade = 0

        .Weight = xlThin

    End With

‘Отображается правая граница диапазона

    With Selection.Borders(xlEdgeRight)

        .LineStyle = xlContinuous

        .ColorIndex = 0

        .TintAndShade = 0

        .Weight = xlThin

    End With

‘Отображаются внутренние вертикальные линии

    With Selection.Borders(xlInsideVertical)

        .LineStyle = xlContinuous

        .ColorIndex = 0

        .TintAndShade = 0

        .Weight = xlThin

    End With

‘Отображаются внутренние горизонтальные линии

    With Selection.Borders(xlInsideHorizontal)

        .LineStyle = xlContinuous

        .ColorIndex = 0

        .TintAndShade = 0

        .Weight = xlThin

    End With

End Sub

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

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

Создание и удаление диагональных линий

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

‘Создание диагональных линий:

Range(«A1:G7»).Borders(xlDiagonalDown).LineStyle = True

Range(«A1:G7»).Borders(xlDiagonalUp).LineStyle = True

‘Удаление диагональных линий:

Range(«A1:G7»).Borders(xlDiagonalDown).LineStyle = xlNone

Range(«A1:G7»).Borders(xlDiagonalUp).LineStyle = xlNone

Расположение границ ячеек и диапазонов

Расположение границ по краям и внутри ячеек и диапазонов описывают константы из коллекции XlBordersIndex.

Список констант XlBordersIndex:

Константа Значение Описание
xlDiagonalDown 5 Диагональная линия от верхнего левого угла к нижнему правому углу в каждой ячейке диапазона.
xlDiagonalUp 6 Диагональная линия от нижнего левого угла к правому верхнему углу в каждой ячейке диапазона.
xlEdgeBottom 9 Граница по нижнему краю диапазона.
xlEdgeLeft 7 Граница по левому краю диапазона.
xlEdgeRight 10 Граница по правому краю диапазона.
xlEdgeTop 8 Граница по верхнему краю диапазона.
xlInsideHorizontal 12 Горизонтальные границы для всех ячеек в диапазоне, за исключением внешних границ диапазона.
xlInsideVertical 11 Вертикальные границы для всех ячеек в диапазоне, за исключением внешних границ диапазона.

‘Отображаем у выделенной ячейки нижнюю границу с толщиной и стилем по умолчанию (xlThin и xlContinuous)

ActiveCell.Borders(xlEdgeBottom).LineStyle = True

ActiveCell.Borders(xlEdgeBottom).LineStyle = 1

Толщина границ ячеек и диапазонов

Толщину границ по краям и внутри ячеек и диапазонов описывают константы из коллекции XlBorderWeight.

Список констант XlBorderWeight:

Константа Значение Описание
xlHairline 1 Очень тонкая граница
xlThin 2 Тонкая граница (по умолчанию)
xlMedium -4138 | 3* Граница средней толщины
xlThick 4 Толстая граница

* У меня, в Excel 2016, константе xlMedium соответствует не только числовое значение -4138, но и 3.

‘Отображаем у выделенной ячейки нижнюю границу в виде толстой линии

ActiveCell.Borders(xlEdgeBottom).Weight = xlThick

Стили границ (типы линий)

Стили границ по краям и внутри ячеек и диапазонов описывают константы из коллекции XlLineStyle.

Список констант XlLineStyle:

Константа Значение Описание
xlContinuous 1 Непрерывная линия
xlDash -4115 Штриховая линия
xlDashDot 4 Чередование точек и тире
xlDashDotDot 5 Чередование двух точек и тире
xlDot -4118 Пунктирная линия
xlDouble -4119 Двойная линия
xlLineStyleNone -4142 Нет границы (удаление границы)
xlSlantDashDot 13 Линия, разрезанная двойными слешами

Применяем разные типы линий к разным сторонам выделенного диапазона:

Sub Primer()

    With Selection

        .Borders(xlEdgeTop).LineStyle = xlDash

        .Borders(xlEdgeTop).Weight = xlMedium

        .Borders(xlEdgeRight).LineStyle = xlDouble

        .Borders(xlEdgeBottom).LineStyle = xlDot

        .Borders(xlEdgeLeft).LineStyle = xlDashDot

    End With

End Sub

Какие могут быть границы в сочетаниях типа линии и ее толщины, вы можете видеть в диалоговом окне «Формат ячеек» на вкладке «Граница».


В данном примере описаны макросы для автоматического форматирования или спроса формата для ячеек таблиц Excel средствами VBA.

VBA-макрос: заливка, шрифт, линии границ, ширина столбцов и высота строк

В процессе запыления данных сотрудниками отдела на некоторых листах были изменены форматы ячеек:

запыления планов работ.

Необходимо сбросить форматирование ячеек и сделать так чтобы на всех таблицах планов выполнения работ были одинаковые форматы отображения данных. Формат ячеек для исходной таблицы должен быть закреплен за шаблоном, чтобы можно было сделать сброс и применять заданный стиль оформления в дальнейшем.

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

Макросы Excel прекрасно справляются с форматированием ячеек на рабочих листах. Кроме того, делают это быстро и в полностью автоматическом режиме. Воспользуемся этими преимуществами и для решения данной задачи напишем свой код VBA-макроса. Он поможет нам быстро и безопасно сбрасывать форматы на исходный предварительно заданный в шаблоне главной таблицы.

Чтобы написать свой код макроса откройте специальный VBA-редактор в Excel: «РАЗРАБОТЧИК»-«Код»-«Visual Basic» или нажмите комбинацию клавиш ALT+F11:

Код Visual Basic.

В редакторе создайте новый модуль выбрав инструмент «Insert»-«Module» и введите в него такой VBA-код макроса:

Sub SbrosFormat()
If TypeName(Selection) <> "Range" Then Exit Sub
With Selection
.HorizontalAlignment = xlVAlignCenter
.VerticalAlignment = xlVAlignCenter
.WrapText = True
.Borders.LineStyle = xlContinuous
.Borders.Weight = xlThin
.Font.ColorIndex = xlColorIndexAutomatic
.Interior.ColorIndex = xlColorIndexAutomatic
.Columns.AutoFit
.Rows.AutoFit
End With
End Sub

VBA-код макроса.

Теперь если нам нужно сбросить форматирование таблицы на исходный формат отображения ее данных, выделите диапазон ячеек A1:E20 и запустите макрос: «РАЗРАБОЧТИК»-«Код»-«Макросы»-«SbrosFormat»-«Выполнить». Результат работы макроса изображен ниже на рисунке:

сбросить форматирование таблицы на исходный формат.

Таблица приобрела формат, который определен макросом. Таким образом код VBA нам позволяет сбросить любые изменения формата ячеек на предустановленный автором отчета.



Описание VBA-макроса для формата ячеек таблицы Excel

Первая инструкция в коде, проверяет выделены ли ячейки диапазоном. Если перед выполнением макроса выделил другой элемент листа, например, график, тогда макрос закрывается и дальнейшие инструкции выполняться не будут. В противные случаи будут форматироваться все выделенные ячейки по очереди в соответствии с определенными настройками форматирования:

  1. Текст в значениях ячеек выравнивается по центру горизонтально и вертикально.
  2. Включен построчный перенос текста.
  3. Все границы ячеек получают черную обычной толщины непрерывную линию с черным цветом.
  4. Сброс цвета шрифта на авто.
  5. Удаляется любая заливка ячеек.
  6. Ширина столбцов автоматически настраивается под текст в ячейках.
  7. Автоматически настроить высоту строк по содержимому ячеек.

Модификация исходного кода макроса для форматирования

Если необходимо сделать так чтобы текст выравнивался не по центру относительно горизонтали, а по правую сторону ячейки, тогда измените константу xlHAlignCenter на xlHAlignRight. Она находиться в свойстве .HorizontalAlignment. Сделайте это следующим образом:

.HorizontalAlignment = xlHAlignRight.

Таким же образом можно выровнять текст по левую сторону изменив значение константы на xlHAlignLeft. Или можно выровнять положение текста по ширине ячейки используя константу xlHAlignJustify.

Чтобы макрос выравнивал текст в ячейках по вертикали к низу, измените строку кода, отвечающую за данную настройку форматирования. Измените константу, которая присваивается к свойству VerticalAlignment в следующий способ:

Если хотите выровнять текс к верху ячейки, тогда воспользуйтесь константой xlHAlignTop.

Если нужно применить для границ ячеек толстую и пунктирную линию в синем цвете, смодифицируйте инструкцию, отвечающую за формат линий:

.Borders.LineStyle = xlDash

.Borders.Color = vbBlue

.Borders.Weight = xlMedium

Описание настройки форматирования для линий границ ячеек. Мы будем получать разные дополнительные типы линий границ если для свойства LineStyle присваивать такие константы:

  • xlDoshDot – применяется для рисования пунктирных линий в границах ячеек;
  • xlDouble – рисует двойную линию;
  • xlHairLine – рисует тонкую линию;
  • xlThick – для рисования очень толстой линии.

Для настройки цвета линий Excel предлагает всего 8 констант для определенных цветов. Константы для настройки цвета линий границ для свойства Color:

  • vbBlack – черный;
  • vbWhite – белый;
  • vbRed – красный;
  • vbGreen –зеленый;
  • vbBlue – синий;
  • vbYellow – желтый;
  • vbMagenta – алый;
  • vbCyan – голубой.

Но при необходимости присвоить линиям границ другие цвета можно вместо константы для свойства Color записать функцию RGB(). Достаточно лишь в аргументе этой функции указать код цвета по шкале от 0 и до 255.

Если нужно применить толстую линию только для границ выделенного диапазона, тогда перед инструкцией End With добавьте следующую строку кода:

.BorderAround xlContinuous, xlMedium, vbBlack

Описание: В первом аргументе для метода BorderAround можно записать также другой стиль линии. Во втором – толщину линии, а в третьем – цвет. Константы, которые можно присвоить в качестве значений для этих аргументов можно использовать те же, которые мы использовали для свойств: LineStyle, Weight, Color.

Если нужно экспонировать первую строку для выделенного диапазона с помощью жирного и курсивного шрифта значений ячеек. А также заполнить ячейки первой строки заливкой с голубым цветом, тогда в самом конце кода макроса перед последней инструкцией End Sub следует добавить несколько строк с VBA-кодом:

.Rows(1).Font.Bold = True

.Rows(1).Font.Italic = True

.Rows(1).Interior.Color = vbCyan

Если хотите присвоить такой же формат для не только для первой строки, но и для первого столбца выделенного диапазона, тогда скопируйте и вставьте ниже эти 3 строчки кода. После в последних трех строках измените свойство Rows на Columns.

.Columns (1).Font.Bold = True

.Columns (1).Font.Italic = True

.Columns (1).Interior.Color = vbCyan

Если нужно задать особенный формат для экспонирования последней строки выделенного диапазона, тогда измените число 1 в аргументе свойства Rows на число всех выделенных строк .Rows.Count. Например, добавьте в конец кода еще такую строку:

.Rows(.Rows.Count).Font.Bold = True

Полная версия модифицированного кода макроса выглядит так:

Sub SbrosFormat()
If TypeName(Selection) <> "Range" Then Exit Sub
With Selection
.HorizontalAlignment = xlVAlignCenter
.VerticalAlignment = xlVAlignCenter
.WrapText = True
.Borders.LineStyle = xlDash
.Borders.Color = vbBlue
.Borders.Weight = xlMedium
.Font.ColorIndex = xlColorIndexAutomatic
.Interior.ColorIndex = xlColorIndexAutomatic
.Columns.AutoFit
.Rows.AutoFit
.BorderAround xlContinuous, xlMedium, vbBlack
.Rows(1).Font.Bold = True
.Rows(1).Font.Italic = True
.Rows(1).Interior.Color = vbCyan
.Columns(1).Font.Bold = True
.Columns(1).Font.Italic = True
.Columns(1).Interior.Color = vbCyan
.Rows(.Rows.Count).Font.Bold = True
End With
End Sub

Пример работы измененного кода VBA-макроса:

Пример после изменений в коде.

В данном примере вы ознакомились с базовыми возможностями форматирования с помощью VBA-макросов. Уверен, что теперь вы сможете самостоятельно найти практическое применение этим исходным кодам.

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

To apply borders to a cell using VBA in Excel, you can use two different ways. The first is the “Borders“ property and the second is the “BorderAround” method. The only difference between these two ways is in the “Borders” property you can even apply the border to one side of the cell and in the border around it applies to the cell completely.

In this tutorial, we will explore both ways and look at what are the different ways to add the border.

VBA Border Property

  1. First, you need to specify the range or the cell where you wish to apply the border using the range object.
    1-specify-the-range-or-cell
  2. After that, type a dot (.) and then select the “Borders” property from the list of properties and methods.
    2-type-a-dot-and-then-select-the-border
  3. Next, specify the border index from the contants avaiable. Here I’m using “xlEdgeBottom” to apply border only to the bottom of the cell.
    3-specify-the-border-index
  4. From here, specify the line style using the “LineStyle”. I’m using the “xlContinuonus” as the line style.
    4-specify-the-line-style
Sub vba_borders()

Range("A1") _
        .Borders(xlEdgeBottom) _
            .LineStyle = XlLineStyle.xlContinuous

End Sub

Now when you run this code, it will add a border to the bottom of the cell A1.

Using Different Colors with Color Index/Color

Just like you normally choose the color for the border when you do it manually. In the border property, you can further use the color index and color property to use a color other than the default color.

Consider the below code.

With Range("A1").Borders(xlEdgeBottom)

            .LineStyle = XlLineStyle.xlContinuous
            .Color = RGB(255, 0, 0)

End With

When you run this macro, it adds a border to the bottom of the cell with a red color.

Or if you want to use the colorindex property then the code would be like.

With Range("A1").Borders(xlEdgeBottom)

            .LineStyle = XlLineStyle.xlContinuous
            .ColorIndex = 7

End With

Related: VBA With Statement

Add Border Inside a Cell

If you want to apply a border inside a cell, in that case, you need to use “xlDiagonalUp” and “xlDiagonalDown” as the xlBorderIndex.

With Range("A1").Borders(xlDiagonalUp)

            .LineStyle = XlLineStyle.xlDashDotDot
            .Color = RGB(255, 0, 0)

End With

With Range("A1").Borders(xlDiagonalDown)

            .LineStyle = XlLineStyle.xlDashDotDot
            .Color = RGB(255, 0, 0)

End With

When you run the above code, it adds a border inside the cell upward and downward.

VBA BorderAround Method

In VBA’s BorderAround property you have 5 arguments to which are optional but two need to be specified to apply the border to a cell in the right way.

The following code applies the border around the range A1:A3 when you run the macro.

Range("A1:A3").BorderAround _
                LineStyle:=xlContinuous, _
                Weight:=xlThin

Add Border to Each Cell in the Range

The following code loops through all the cells in the range and applies the border to each cell one by one.

Sub vba_borders()

Dim iRange As Range
Dim iCells As Range

Set iRange = Range("A1:A10")

For Each iCells In iRange
    iCells.BorderAround _
            LineStyle:=xlContinuous, _
            Weight:=xlThin
Next iCells

End Sub

Apply Border to All the Cells with Text

The following code uses a FOR LOOP, USED RANGE, IFEMPTY, and IF STATEMENT  to apply borders to the only cells where you have value.

Dim iRange As Range
Dim iCells As Range

Set iRange = ThisWorkbook.ActiveSheet.UsedRange

For Each iCells In iRange
    If Not IsEmpty(iCells) Then
    iCells.BorderAround _
            LineStyle:=xlContinuous, _
            Weight:=xlThin
    End If
Next iCells

Remove Borders

You just need to use line style “xlNone”.  

Range("A1").Borders(xlDiagonalDown).LineStyle = xlNone

And if you want to remove the border from all the cells in a worksheet where you have a value, consider the following code.

Dim iRange As Range
Dim iCells As Range

Set iRange = ThisWorkbook.ActiveSheet.UsedRange

For Each iCells In iRange
    If Not IsEmpty(iCells) Then
        iCells.Borders(xlDiagonalDown).LineStyle = xlNone
    End If
Next iCells

More Tutorials

    • Count Rows using VBA in Excel
    • Excel VBA Font (Color, Size, Type, and Bold)
    • Excel VBA Hide and Unhide a Column or a Row
    • Excel VBA Range – Working with Range and Cells in VBA
    • Find Last Row, Column, and Cell using VBA in Excel
    • Insert a Row using VBA in Excel
    • Merge Cells in Excel using a VBA Code
    • Select a Range/Cell using VBA in Excel
    • SELECT ALL the Cells in a Worksheet using a VBA Code
    • ActiveCell in VBA in Excel
    • Special Cells Method in VBA in Excel
    • UsedRange Property in VBA in Excel
    • VBA AutoFit (Rows, Column, or the Entire Worksheet)
    • VBA ClearContents (from a Cell, Range, or Entire Worksheet)
    • VBA Copy Range to Another Sheet + Workbook
    • VBA Enter Value in a Cell (Set, Get and Change)
    • VBA Insert Column (Single and Multiple)
    • VBA Named Range | (Static + from Selection + Dynamic)
    • VBA Range Offset
    • VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
    • VBA Wrap Text (Cell, Range, and Entire Worksheet)
    • VBA Check IF a Cell is Empty + Multiple Cells

    ⇠ Back to What is VBA in Excel

    Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes

    Borders in VBA Excel

    We use borders in Excel to highlight our data. In any dashboard, it is a very important skill to represent the important data, and borders do it. Borders are a property in VBA that we can access using the Range method and giving the appropriate border style as we know there are different border styles.

    If you are good at formatting in excelFormatting is a useful feature in Excel that allows you to change the appearance of the data in a worksheet. Formatting can be done in a variety of ways. For example, we can use the styles and format tab on the home tab to change the font of a cell or a table.read more, you can call yourself an “Excel Beautician.” Formatting is vital in making the reports look appealing to the end-user or readers. We hope you are well aware of the formatting techniques in the regular worksheet. Formatting through VBA codingConditional formatting is also possible in Excel VBA programming by using the ‘Format Conditions Collection’ macro/procedure. A conditional format is one that is applied only to cells that meet certain criteria, such as values above a certain threshold, positive or negative values, or values with a specific formula, and so on.read more requires a considerable amount of VBA coding languageVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. This article will show you one of the most underrated formatting techniques, i.e., applying Excel VBA borders.

    Table of contents
    • Borders in VBA Excel
      • Examples of Borders in VBA
        • Example #1 – Apply VBA Borders with Coding
        • Example #2 – Change the Border Using VBA Borders Around Method
      • Recommended Articles

    VBA Borders

    You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
    For eg:
    Source: VBA Borders (wallstreetmojo.com)

    Examples of Borders in VBA

    Let us take a look at some examples to understand this in a better manner.

    You can download this VBA Borders Excel Template here – VBA Borders Excel Template

    Example #1 – Apply VBA Borders with Coding

    Creating a macro to apply Excel VBA borders with different styles, making them available as an add-on to the excelAn add-in is an extension that adds more features and options to the existing Microsoft Excel.read more ribbon, makes the job easier whenever we want to apply VBA borders.

    Every cell in a worksheet has borders and background colors. By default, every cell has no border and background color.

    In the worksheet under the HOME tab, we have a border option. In addition, we have various options if you click on the drop-down list in excelA drop-down list in excel is a pre-defined list of inputs that allows users to select an option.read more.

    VBA Borders Example 1

    But in VBA, first, we must decide on the cell or range of cells. Then, we will apply the Excel VBA borders formatting styles. So, we can refer to the range of cells or cells using VBA RANGEThe range property of VBA is used to refer to any data, cells, or selection. It is an inbuilt property that allows us to access any part of the worksheet. Using the range property for a single cell-like range is referred to as range cells.read more object. So, for example, if you want to change the border of cell B5, then you can write the code like this.

    Range(“B5”)

    Then, we need to access the “Borders” property.

    Code:

    Sub Border_Example1()
    
      Range("B5").Bo
    
    End Sub

    VBA Borders Example 1-1

    After applying the Excel VBA “Borders” property, we must open parenthesis to see all border formatting options..

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(
    
    End Sub

    VBA Borders Example 1-2

    Here, we have xlDiagonalDown, xlDiagonalUp, xlEdgeBottom, xlEdgeLeft, xlEdgeRight, xlEdgeTop, xlInsideHorizontal, and xlInsideVertical.

    VBA Borders Example 1-3

    After selecting the border style, we need to select the characteristic we want to work with. One of the characters we need to use here is “LineStyle,” so select the “LineStyle” property.

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders (xlEdgeBottom).li
    
    End Sub

    VBA Borders Example 1-4

    Once the line style property is selected, we need to set the line style type of line or type of borders we will apply in VBA.

    Put an equal sign and select “XlLineStyle” enumeration.

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle =XlLineStyle.
    
    End Sub

    VBA Borders Example 1-5

    Put a dot to see all the available border styles.

    Code:

    VBA Borders Example 1-6

    We have many options here. xlContinuous, xldash, xlDashDot, xlDashDotDot, xlDot, xlDouble, XlLineStyleNone, and xlSlantDashDot.

    Now, we have selected the option of “xlDouble.”

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlDouble
    
    End Sub

    Now, if I run the code, it will apply the Double line to the bottom of cell B5.

    VBA Borders Example 1-7

    Line Type: “xlContinuous”.

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
    
    End Sub

    Result:

    VBA Borders Example 1-8

    Line Type: “clash.”

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlDash
    
    End Sub

    Result:

    VBA Borders Example 1-9

    Line Type: “xlDashDot.”

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlDashDot
    
    End Sub

    Result:

    VBA Borders Example 1-10

    Line Type: “xlDashDotDot”.

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlDashDotDot
    
    End Sub

    Result:

    VBA Borders Example 1-11

    Line Type: “xlDot.”

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlDot
    
    End Sub

    Result:

    Example 1-12

    Line Type: “xlLineStyleNone”.

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlLineStyleNone
    
    End Sub

    Result:

    Example 1-13

    It will remove the border of the specified cell.

    Line Type: “xlSlantDashDot”.

    Code:

    Sub Border_Example1()
    
      Range("B5").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlSlantDashDot
    
    End Sub

    Result:

    Example 1-14

    Example #2 – Change the Border Using VBA Borders Around Method

    We can also change the cell’s borders using the VBA Borders Around method. Once we mention the range of cells or cells, we need to access the VBA Borders Around method.

    Example 2

    Open parenthesis to see all the parameters.

    Range(“B5”).BorderAround([Line Style], [Weight as xlBorderWeight], [ColorIndex], [Color], [Theme Color])

    We can mention the line style, color, border weight, and many more things we can do with this method.

    Code:

    Sub Border_Example1()
    
      Range("B5").BorderAround LineStyle:=xlContinuous, Weight:=xlThick
    
    End Sub

    It will change the Line Style to xlContinuous.

    LineStyle:=xlContinuous

    The weight of the Border is thick.

    Weight:=xlThick

    And the result of this code is as below.

    Example 2-1

    Like this, using Excel VBA Borders and Border Around property and method, we can change the border and elements of borders through VBA coding.

    Recommended Articles

    This article has been a guide to VBA Borders. Here, we learn how to set borders with Excel VBA coding, practical examples, and downloadable code templates. You may also have a look at other articles related to Excel VBA: –

    • What are Global Variables in Excel VBA?
    • Examples to Create a Pivot Table in VBA
    • Excel VBA End
    • Conditional Formatting for Blank Cells

    Excel VBA Border

    Borders in Excel VBA

    Borders are a necessary part of every worksheet or in any word file. Borders separate data from one another it shows which part of data is referred to which area to avoid any confusion. Also, it looks good to have borders in our datasheet. In excel worksheet we have options for inserting borders manually, but how we do it in VBA is what we will learn in this article.

    To apply borders in VBA we need to access the properties of a cell and in the current case, the property we need to access is borders. Now we need to keep in mind that there are various types of options available in borders properties. Such as diagonal vertical up down etc. We will cover some of them here.

    How to Use Borders in VBA

    To use borders in VBA we need to follow these steps as follows:

    1. Use range method to access the range value.
    2. Use borders method if we want to format only a portion of cell or borders around if we want to cover the cells with borders.
    3. Use different line styles to make the borders look pleasant.

    You can download this VBA Border Excel Template here – VBA Border Excel Template

    Now let us go through some examples and see how we can insert a border in excel cell.

    Example #1 – VBA Borders

    Let us use the basic enumerations what VBA provides us when we type the keywords to see the borders. We will put borders in cell A1 and see the result.

    Step 1: Go to Developer’s tab, open visual basic and we will see a VB Editor.

    Developer's Tab

    Step 2: Insert a new module from the insert tab provided. Click on the module we just inserted which will open a code window for us,

    Module

    Step 3: Declare a sub-function which means naming our macro.

    Code:

    Sub Sample()
    
    End Sub

    Sub Function

    Step 4: Activate the worksheet first in order to use its properties by the following code below,

    Code:

    Sub Sample()
    
    Worksheets("Sheet1").Activate
    
    End Sub

    VBA Border Example 1.2

    Step 5: Now let us try to change the border of cell A1. Use the range method as below,

    Code:

    Sub Sample()
    
    Worksheets("Sheet1").Activate
    Range("A1").Borders
    
    End Sub

    VBA Border Example 1.3

    Step 6: Select the borders properties which will give us an option to select the border style as follows,

    Code:

    Sub Sample()
    
    Worksheets("Sheet1").Activate
    Range("A1").Borders(
    
    End Sub

    Border Example 1.5

    Step 7: Select the first option which is Xdiagonalup as the border style.

    Code:

    Sub Sample()
    
    Worksheets("Sheet1").Activate
    Range("A1").Borders (xlDiagonalUp)
    
    End Sub

    Bdr Example 1.6

    Step 8: Now we need to use the line style for borders. After dot(.) operator use enumerations for line style as follows,

    Code:

    Sub Sample()
    
    Worksheets("Sheet1").Activate
    Range("A1").Borders(xlDiagonalUp).LineStyle
    
    End Sub

    Bdr Example 1.7

    Step 9: Type = sign and it will give us the numerous enumerations for linestyle as follows,

    Code:

    Sub Sample()
    
    Worksheets("Sheet1").Activate
    Range("A1").Borders(xlDiagonalUp).LineStyle = XlLineStyle.xlDouble
    
    End Sub

    Bdr Example 1.8

    Step 10: Let us run the above code by pressing F5 and see the result in sheet 1 as follows,

    VBA Border 1

    Example #2 – VBA Border

    Now let us use the other method for the border style in VBA.

    Step 1: We already have our module inserted, Name a macro in it with another sub-function as follows,

    Code:

    Sub Sample1()
    
    End Sub

    VBA Border Example 2.1

    Step 2: Activate the worksheet by the following code written below,

    Code:

    Sub Sample1()
    
    Worksheets("Sheet1").Activate
    
    End Sub

    Bdr Example 2.2

    Step 3: Now let use the range method to activate the border properties such as shown below,

    Code:

    Sub Sample1()
    
    Worksheets("Sheet1").Activate
    Range("C1").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlDashDot
    
    End Sub

    Bdr Example 2.3

    Step 4: Now run the above code and see the result in Sheet 1 as follows,

    VBA border 2

    Example #3 – VBA Border

    Let us try a few more of the border and line styles in another cell. This time we will use it in a cell range C5:E6.

    Step 1: We already have our module inserted, Name a macro in it with another sub-function as follows,

    Code:

    Sub Sample2()
    
    End Sub

    VBA Border Example 3.1

    Step 2: Activate the worksheet by the following code written below,

    Code:

    Sub Sample2()
    
    Worksheets("Sheet3").Activate
    
    End Sub

    VBA Border Example 3.2

    Step 3: Now let use the range method to activate the border properties such as shown below,

    Code:

    Sub Sample2()
    
    Worksheets("Sheet3").Activate
    Range("C5:E6").Borders(xlEdgeTop).LineStyle = XlLineStyle.xlSlantDashDot
    
    End Sub

    Bdr Example 3.3

    Step 4: Now run the above code and see the result in Sheet 1 as follows,

    VBA Border 3

    Example #4 – VBA Border

    Now in this example, we will use borders around the cell covering the whole cell. Earlier what we did was border only one portion of the cell. Consider the following data we have in sheet 2 as follows,

    VBA Border Example 4.1

    Let us try to use a border around this data using the border around the method.

    Step 1: We already have our module inserted, Name a macro in it with another sub-function as follows,

    Code:

    Sub Sample3()
    
    End Sub

    VBA Border Example 4.2

    Step 2: Activate the worksheet by the following code written below,

    Code:

    Sub Sample3()
    
    Worksheets("Sheet2").Activate
    
    End Sub

    Bdr Example 4.3

    Step 3: Now let’s use the range method to activate the border around properties such as shown below,

    Code:

    Sub Sample3()
    
    Worksheets("Sheet2").Activate
    Range("A1:B6").BorderAround
    
    End Sub

    Bdr Example 4.4

    Step 4: Now use the line style and line thickness as follows,

    Code:

    Sub Sample3()
    
    Worksheets("Sheet2").Activate
    Range("A1:B6").BorderAround LineStyle:=xlContinuous, Weight:=xlThick
    
    End Sub

    Bdr Example 4.5

    Step 5: Run the above code by pressing F5 and see the result in sheet 2 as follows,

    VBA Border 4

    Things to Remember

    • Border around is used to cover all parts of cells.
    • Borders method is used to cover only a portion of a cell.
    • X Linestyles are used to use different types of styles in borders.
    • Inserting borders is similar to formatting data.
    • Borders in VBA are similar to borders in the worksheet, we need to remember the keyword for it to use.

    Recommended Articles

    This is a guide to VBA Borders. Here we discuss how to use Borders in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

    1. VBA IsNumeric
    2. VBA UCASE
    3. VBA Worksheets
    4. VBA RGB

    You can add border to any range in a very dynamic way by using the AddBorder and GetCurrentRegionStartingGivenCell function in Xatocode as follows:

    ' First you may define a worksheet level named range in starting cell and name it as rngData
    Sub BorderExample()
    
        Dim rngData         As Range ' Range to sort
    
        Set rngData = GetCurrentRegionStartingGivenCell(shtData.Range("rngData"))
    
        Call AddBorder(rngData, EdgeLeft)
        Call AddBorder(rngData, EdgeTop)
        Call AddBorder(rngData, EdgeRight)
        Call AddBorder(rngData, EdgeBottom)
        Call AddBorder(rngData, InsideVertical)
        Call AddBorder(rngData, InsideHorizontal)
        Call AddBorder(rngData, DiagonalUp)
        Call AddBorder(rngData, DiagonalDown)
        Call ClearBorder(rngData)
        Call AddBorder(rngData, Box)
        Call AddBorder(rngData, AllBorder)
        Call AddBorder(rngData, AllBorder, xlDot) ' Linestyle
        Call AddBorder(rngData, AllBorder, , xlMedium) ' Thickness
        Call AddBorder(rngData, AllBorder, , , vbRed) ' Color
    End Sub
    

    You can read the complete article here

    Formatting Excel Cells can be automated to save a lot of time. Below you can find code samples for formatting Excel cells.

    Formatting Cell Interior

    You have at least 2 options to set a Cell background color in VBA. The first is setting by using the Color property by setting it to a value using the VBA RGB function and specifying its R (Red), G (Green), B (Blue) components. The second is using the ThemeColor property and setting it to constant representing a default Theme color:

    'Alternative ways to set the cell background color
    With Range("A1").Interior
    'Sets the background color to an RGB value (Red,Green,Blue)
     .Color = RGB(255,0,0) 'Green
    'Sets the background color to the Theme color accent 1 color
     .ThemeColor = xlThemeColorAccent1 
    'Sets the background color to the ColorIndex
     .ColorIndex = 1 '1=Black, 2=White, 3=Red ..etc. Check link below for more
    End With
    

    You can read more on the difference between the VBA ColorIndex and VBA Color property here.

    'Alternative ways to set the cell background color
    With Range("A1").Font
    'Sets the font color to RGB value. See Interior row above for more color options
     .Color = RGB(0,255,0) 
    'Sets font as Italic
     .Italic = true
    'Sets font as bold
     .Bold = true
    'Sets the name of the font e.g. Arial, Times New Roman
     .Name = "Agency FB"
    'Set the size of the font
     .Size = 11
    'Sets strikethrough
    .Strikethrough = True
    'Sets as either super or subscript (mutually exclusive)
    .Superscript = False
    .Subscript = True
    End With
    

    Formatting Cell Borders

    To set borders of Excel Cells in VBA you need to use the Borders property:

    'Set all borders to continuous and thin
     With Range("A1").Borders
     .LineStyle = xlContinuous
     .Weight = xlThin
    'Sets the border color to RGB value. See Interior row above for more color options
     .Color = RGB(0,255,0) 
    End With
    'Set only top border as continuos and thin
    With Range("A1").Borders(xlEdgeTop)
     .LineStyle = xlContinuous
     .Weight = xlThin
    End With
    

    Possible LineStyles:

    • xlContinuous
    • xlDash
    • xlDashDot
    • xlDashDotDot
    • xlDot
    • xlDouble
    • xlSlantDashDot
    • xlLineStyleNone

    Possible borders (Index):

    • xlDiagonalDown
    • xlDiagonalUp
    • xlEdgeBottom
    • xlEdgeLeft
    • xlEdgeRight
    • xlEdgeTop
    • xlInsideHorizontal
    • xlInsideVertical

    Formatting Cell Alignment

    Excel Cell alignment can be modified by a couple of ways. The first is using HorizontalAlignment and VerticalAlignment properties. Additionally you can set indentation using the InsertIndent procedure.

    'Increase or decrease cell indent
    Range("A1").InsertIndent 1
    Range("A1").InsertIndent -1
    
    'Align to left, bottom
    With Range("A1").
     .HorizontalAlignment = xlLeft 'or xlRight
     .VerticalAlignment = xlBottom 'or xlTop
    End With
    
    'Set wrap text to true
    Range("A1").WrapText = True
    
    'Set cell orientation to 45 degrees
    Range("A1").Orientation = 45
    

    Понравилась статья? Поделить с друзьями:
  • Vba excel отфильтровать таблицу
  • Vba excel открыть файл excel в той же папке
  • Vba excel открыть страницу
  • Vba excel открыть проводник
  • Vba excel открыть приложение