Vba format cell in excel

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

Formatting Cells Number

General

Range("A1").NumberFormat = "General"

Number

Range("A1").NumberFormat = "0.00"

Currency

Range("A1").NumberFormat = "$#,##0.00"

Accounting

Range("A1").NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(@_)"

Date

Range("A1").NumberFormat = "yyyy-mm-dd;@"

Time

Range("A1").NumberFormat = "h:mm:ss AM/PM;@"

Percentage

Range("A1").NumberFormat = "0.00%"

Fraction

Range("A1").NumberFormat = "# ?/?"

Scientific

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

Text

Range("A1").NumberFormat = "@"

Special

Range("A1").NumberFormat = "00000"

Custom

Range("A1").NumberFormat = "$#,##0.00_);[Red]($#,##0.00)"

Formatting Cells Alignment

Text Alignment

Horizontal

The value of this property can be set to one of the constants: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight.

The following code sets the horizontal alignment of cell A1 to center.

Range("A1").HorizontalAlignment = xlCenter

Vertical

The value of this property can be set to one of the constants: xlBottom, xlCenter, xlDistributed, xlJustify, xlTop.

The following code sets the vertical alignment of cell A1 to bottom.

Range("A1").VerticalAlignment = xlBottom

Text Control

Wrap Text

This example formats cell A1 so that the text wraps within the cell.

Range("A1").WrapText = True

Shrink To Fit

This example causes text in row one to automatically shrink to fit in the available column width.

Rows(1).ShrinkToFit = True

Merge Cells

This example merge range A1:A4 to a large one.

Range("A1:A4").MergeCells = True

Right-to-left

Text direction

The value of this property can be set to one of the constants: xlRTL (right-to-left), xlLTR (left-to-right), or xlContext (context).

The following code example sets the reading order of cell A1 to xlRTL (right-to-left).

Range("A1").ReadingOrder = xlRTL

Orientation

The value of this property can be set to an integer value from –90 to 90 degrees or to one of the following constants: xlDownward, xlHorizontal, xlUpward, xlVertical.

The following code example sets the orientation of cell A1 to xlHorizontal.

Range("A1").Orientation = xlHorizontal

Font

Font Name

The value of this property can be set to one of the fonts: Calibri, Times new Roman, Arial

The following code sets the font name of range A1:A5 to Calibri.

Range("A1:A5").Font.Name = "Calibri"

Font Style

The value of this property can be set to one of the constants: Regular, Bold, Italic, Bold Italic.

The following code sets the font style of range A1:A5 to Italic.

Range("A1:A5").Font.FontStyle = "Italic"

Font Size

The value of this property can be set to an integer value from 1 to 409.

The following code sets the font size of cell A1 to 14.

Range("A1").Font.Size = 14

Underline

The value of this property can be set to one of the constants: xlUnderlineStyleNone, xlUnderlineStyleSingle, xlUnderlineStyleDouble, xlUnderlineStyleSingleAccounting, xlUnderlineStyleDoubleAccounting.

The following code sets the font of cell A1 to xlUnderlineStyleDouble (double underline).

Range("A1").Font.Underline = xlUnderlineStyleDouble

Font Color

The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.

To assist you with specifying the color of anything, the VBA is equipped with a function named RGB. Its syntax is:

Function RGB(RedValue As Byte, GreenValue As Byte, BlueValue As Byte) As long

This function takes three arguments and each must hold a value between 0 and 255. The first argument represents the ratio of red of the color. The second argument represents the green ratio of the color. The last argument represents the blue of the color. After the function has been called, it produces a number whose maximum value can be 255 * 255 * 255 = 16,581,375, which represents a color.

The following code sets the font color of cell A1 to vbBlack (Black).

Range("A1").Font.Color = vbBlack

The following code sets the font color of cell A1 to 0 (Black).

Range("A1").Font.Color = 0

The following code sets the font color of cell A1 to RGB(0, 0, 0) (Black).

Range("A1").Font.Color = RGB(0, 0, 0)

Font Effects

Strikethrough

True if the font is struck through with a horizontal line.

The following code sets the font of cell A1 to strikethrough.

Range("A1").Font.Strikethrough = True

Subscript

True if the font is formatted as subscript. False by default.

The following code sets the font of cell A1 to Subscript.

Range("A1").Font.Subscript = True

Superscript

True if the font is formatted as superscript; False by default.

The following code sets the font of cell A1 to Superscript.

Range("A1").Font.Superscript = True

Border

Border Index

Using VBA you can choose to create borders for the different edges of a range of cells:

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

Line Style

The value of this property can be set to one of the constants: xlContinuous (Continuous line), xlDash (Dashed line), xlDashDot (Alternating dashes and dots), xlDashDotDot (Dash followed by two dots), xlDot (Dotted line), xlDouble (Double line), xlLineStyleNone (No line), xlSlantDashDot (Slanted dashes).

The following code example sets the border on the bottom edge of cell A1 with continuous line.

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

The following code example removes the border on the bottom edge of cell A1.

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

Line Thickness

The value of this property can be set to one of the constants: xlHairline (Hairline, thinnest border), xlMedium (Medium), xlThick (Thick, widest border), xlThin (Thin).

The following code example sets the thickness of the border created to xlThin (Thin).

Range("A1").Borders(xlEdgeBottom).Weight = xlThin

Line Color

The value of this property can be set to one of the standard colors: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite or an integer value from 0 to 16,581,375.

The following code example sets the color of the border on the bottom edge to green.

Range("A1").Borders(xlEdgeBottom).Color = vbGreen

You can also use the RGB function to create a color value.

The following example sets the color of the bottom border of cell A1 with RGB fuction.

Range("A1").Borders(xlEdgeBottom).Color = RGB(255, 0, 0)

Fill

Pattern Style

The value of this property can be set to one of the constants:

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

Protection

Locking Cells

This property returns True if the object is locked, False if the object can be modified when the sheet is protected, or Null if the specified range contains both locked and unlocked cells.

The following code example unlocks cells A1:B22 on Sheet1 so that they can be modified when the sheet is protected.

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

Hiding Formulas

This property returns True if the formula will be hidden when the worksheet is protected, Null if the specified range contains some cells with FormulaHidden equal to True and some cells with FormulaHidden equal to False.

Don’t confuse this property with the Hidden property. The formula will not be hidden if the workbook is protected and the worksheet is not, but only if the worksheet is protected.

The following code example hides the formulas in cells A1 and C1 on Sheet1 when the worksheet is protected.

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

Last Updated on January 11, 2023 by

Formatting cells and fonts in VBA – introduction

Cells as well as other elements of the Excel spreadsheet can be formatted from the VBA code level. The formatting itself can be done in 2 ways. The first way is to set each format using a separate code block.

You can also use the With clause to format cells and fonts. You can refer your object and insert any of formats. You can format any parameters, exactly as if you were doing it directly in Excel spreadsheet. If you do not know how to write a block of code to format any cell or its content, the best way to do this is record this formatting with a macro recorder and then analyze the written code.

In formatting, you can refer to a single cell by referencing Cells () or the range of cells using the Range () object . To carry out this exercise, let’s fill the rang of A1: A20 with any text.

Formatting cells and fonts in VBA - introduction

Formatting cells and fonts in VBA – introduction

Font formatting – How to format fonts in VBA

The easiest way to format fonts, in example by setting its size, is to select the cell, then refer to the font and its specific property, in this case its size. Example is listed below.

'OfficeInside.org
Sub FontFormatingExample()
 Range("A1").Select
 Selection.Font.Size = 20
End Sub

If you would like to format more than one font property at the same time, you don’t need to repeat block of code. In this case, you can use the With clause . As in the first example, you will refer to the selected range. Then, change the font size, make it bold, and set the font to Arial.

'OfficeInside.org 
Sub FontFormatingExample1()

Range("A2").Select
With Selection.Font
.Size = 20
.Bold = True
.Name = "Arial"
End With

End Sub

Font formatting - How to format fonts in VBA

Font formatting – How to format fonts in VBA

In this way, you can format any font property in Excel sheet. Below are listed the most important properties that you can use.

'OfficeInside.org
Sub FontFormatingExample2()

Range("A5").Select
With Selection.Font
.Size = 25 'Font size
.Bold = True 'Font bold True/False
.Color = vbBlack 'Font color
.Italic = True 'italic font True/False
.Name = "Arial" 'Font type like Arial or Times New Roman
.Underline = True 'Text underline True/False
End With

End Sub

In VBA, colors can be set in several different ways. You can use both the official VBA naming preceded by the prefix name vb or the range of the RGB colors.

The name of VBA The name of RGB
vbBlack RGB (0, 0, 0)
vbWhite RGB (255, 255, 255)
vbRed RGB (255, 0, 0)
vbGreen RGB (0, 255, 0)
vbBlue RGB (0, 0, 255)
vbYellow RGB (255, 255, 0)
vbMagenta RGB (255, 0, 255)
vbCyan RGB (0, 255, 255)

Formatting cells – How to format cells in VBA

In cell interiors, as in the case of fonts, you can refer to a single cell interior property. If you want to change the colors, you can also use the colors described in the previous section.

'OfficeInside.org 
Sub InteriorFormatingExample1()
 Range("A4").Select
 Selection.Interior.Color = 65535
End Sub

Using the With clause, you can change the following cell interior properties:

'OfficeInside.org 
Sub InteriorFormatingExample2()
 Range("A12:A14").Select
 With Selection.Interior
 .Pattern = xlSolid 'cell pattern
 .PatternColorIndex = 1 'xlAutomatic 'color pattern from 1 to 56
 .Color = RGB(0, 0, 255) ' You can set interior color using vbColor or RGB
 .TintAndShade = 0 'You can type tint and shade
 .PatternTintAndShade = 0 'You can type tint and shade pattern
 End With
End Sub

Formatting cells - How to format cells in VBA

Formatting cells – How to format cells in VBA

Formatting the selection – How to format the range in VBA

In addition to the fonts and interiors of cells, we can also format the other parameters related to the cell. We can set eg text wrapping or cell merging. A detailed description of the parameters that we can use can be found below.

'OfficeInside.org 
Sub FormatingSelection1()
Range("A15:A20").Select
With Selection
.HorizontalAlignment = xlLeft 'Text aligment left or right: x1Left/xlRight
.VerticalAlignment = xlBottom 'Text aligment top or bottom: xlTop/x1Bottom
.WrapText = False 'Text wrap True/False
.Orientation = -1 'Text orientation -1 auto, 0 vertical, 1 horizontal
.AddIndent = True 'You can add indent: True/False
.IndentLevel = 10 'You can set indent level by typing number of levels
.ShrinkToFit = False 'You can fill text size into cell: True/False
.MergeCells = False 'You can merge cells: True/False
End With
End Sub

Formatting the selection - How to format the range in VBA

Formatting the selection – How to format the range in VBA

All examples ypu can find in this file:

Excercises (You can enter the solution in a comment)

  1. Write a macro that will do the following operations on cells: Fills 5 sheet cells with any text. Then set the font size to 24, use the Arial font. Then bold the font. Change the interior color of the cell to green using RGB colors.

More examples of Excel VBA basics can be found in the Excel VBA Course section and  Excel VBA How To section. If you have any questions about this chapter, you can post them on the forum without logging in.

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. Демонстрация свойств ячейки, как структурной единицы объекта Range, на простых примерах.

Объект Range в VBA Excel представляет диапазон ячеек. Он (объект Range) может описывать любой диапазон, начиная от одной ячейки и заканчивая сразу всеми ячейками рабочего листа.

Примеры диапазонов:

  • Одна ячейка – Range("A1").
  • Девять ячеек – Range("A1:С3").
  • Весь рабочий лист в Excel 2016 – Range("1:1048576").

Для справки: выражение Range("1:1048576") описывает диапазон с 1 по 1048576 строку, где число 1048576 – это номер последней строки на рабочем листе Excel 2016.

В VBA Excel есть свойство Cells объекта Range, которое позволяет обратиться к одной ячейке в указанном диапазоне (возвращает объект Range в виде одной ячейки). Если в коде используется свойство Cells без указания диапазона, значит оно относится ко всему диапазону активного рабочего листа.

Примеры обращения к одной ячейке:

  • Cells(1000), где 1000 – порядковый номер ячейки на рабочем листе, возвращает ячейку «ALL1».
  • Cells(50, 20), где 50 – номер строки рабочего листа, а 20 – номер столбца, возвращает ячейку «T50».
  • Range("A1:C3").Cells(6), где «A1:C3» – заданный диапазон, а 6 – порядковый номер ячейки в этом диапазоне, возвращает ячейку «C2».

Для справки: порядковый номер ячейки в диапазоне считается построчно слева направо с перемещением к следующей строке сверху вниз.

Подробнее о том, как обратиться к ячейке, смотрите в статье: Ячейки (обращение, запись, чтение, очистка).

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

Еще надо добавить, что свойства и методы объектов отделяются от объектов точкой, как в третьем примере обращения к одной ячейке: Range("A1:C3").Cells(6).

Свойства ячейки (объекта Range)

Свойство Описание
Address Возвращает адрес ячейки (диапазона).
Borders Возвращает коллекцию Borders, представляющую границы ячейки (диапазона). Подробнее…
Cells Возвращает объект Range, представляющий коллекцию всех ячеек заданного диапазона. Указав номер строки и номер столбца или порядковый номер ячейки в диапазоне, мы получаем конкретную ячейку. Подробнее…
Characters Возвращает подстроку в размере указанного количества символов из текста, содержащегося в ячейке. Подробнее…
Column Возвращает номер столбца ячейки (первого столбца диапазона). Подробнее…
ColumnWidth Возвращает или задает ширину ячейки в пунктах (ширину всех столбцов в указанном диапазоне).
Comment Возвращает комментарий, связанный с ячейкой (с левой верхней ячейкой диапазона).
CurrentRegion Возвращает прямоугольный диапазон, ограниченный пустыми строками и столбцами. Очень полезное свойство для возвращения рабочей таблицы, а также определения номера последней заполненной строки.
EntireColumn Возвращает весь столбец (столбцы), в котором содержится ячейка (диапазон). Диапазон может содержаться и в одном столбце, например, Range("A1:A20").
EntireRow Возвращает всю строку (строки), в которой содержится ячейка (диапазон). Диапазон может содержаться и в одной строке, например, Range("A2:H2").
Font Возвращает объект Font, представляющий шрифт указанного объекта. Подробнее о цвете шрифта…
HorizontalAlignment Возвращает или задает значение горизонтального выравнивания содержимого ячейки (диапазона). Подробнее…
Interior Возвращает объект Interior, представляющий внутреннюю область ячейки (диапазона). Применяется, главным образом, для возвращения или назначения цвета заливки (фона) ячейки (диапазона). Подробнее…
Name Возвращает или задает имя ячейки (диапазона).
NumberFormat Возвращает или задает код числового формата для ячейки (диапазона). Примеры кодов числовых форматов можно посмотреть, открыв для любой ячейки на рабочем листе Excel диалоговое окно «Формат ячеек», на вкладке «(все форматы)». Свойство NumberFormat диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковый числовой формат. Если нужно присвоить ячейке текстовый формат, записывается так: Range("A1").NumberFormat = "@". Общий формат: Range("A1").NumberFormat = "General".
Offset Возвращает объект Range, смещенный относительно первоначального диапазона на указанное количество строк и столбцов. Подробнее…
Resize Изменяет размер первоначального диапазона до указанного количества строк и столбцов. Строки добавляются или удаляются снизу, столбцы – справа. Подробнее…
Row Возвращает номер строки ячейки (первой строки диапазона). Подробнее…
RowHeight Возвращает или задает высоту ячейки в пунктах (высоту всех строк в указанном диапазоне).
Text Возвращает форматированный текст, содержащийся в ячейке. Свойство Text диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковое содержимое и один формат. Предназначено только для чтения. Подробнее…
Value Возвращает или задает значение ячейки, в том числе с отображением значений в формате Currency и Date. Тип данных Variant. Value является свойством ячейки по умолчанию, поэтому в коде его можно не указывать.
Value2 Возвращает или задает значение ячейки. Тип данных Variant. Значения в формате Currency и Date будут отображены в виде чисел с типом данных Double.
VerticalAlignment Возвращает или задает значение вертикального выравнивания содержимого ячейки (диапазона). Подробнее…

В таблице представлены не все свойства объекта Range. С полным списком вы можете ознакомиться не сайте разработчика.

Простые примеры для начинающих

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

Учтите, что в одном программном модуле у всех процедур должны быть разные имена. Если вы уже копировали в модуль подпрограммы с именами Primer1, Primer2 и т.д., удалите их или создайте еще один стандартный модуль.

Форматирование ячеек

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

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

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

Sub Primer1()

MsgBox «Зальем ячейку A1 зеленым цветом и запишем в ячейку B1 текст: «Ячейка A1 зеленая!»»

Range(«A1»).Interior.Color = vbGreen

Range(«B1»).Value = «Ячейка A1 зеленая!»

MsgBox «Сделаем высоту строки, в которой находится ячейка A2, в 2 раза больше высоты ячейки A1, « _

& «а в ячейку B1 вставим текст: «Наша строка стала в 2 раза выше первой строки!»»

Range(«A2»).RowHeight = Range(«A1»).RowHeight * 2

Range(«B2»).Value = «Наша строка стала в 2 раза выше первой строки!»

MsgBox «Запишем в ячейку A3 высоту 2 строки, а в ячейку B3 вставим текст: «Такова высота второй строки!»»

Range(«A3»).Value = Range(«A2»).RowHeight

Range(«B3»).Value = «Такова высота второй строки!»

MsgBox «Применим к столбцу, в котором содержится ячейка B1, метод AutoFit для автоподбора ширины»

Range(«B1»).EntireColumn.AutoFit

MsgBox «Выделим текст в ячейке B2 красным цветом и выровним его по центру (по вертикали)»

Range(«B2»).Font.Color = vbRed

Range(«B2»).VerticalAlignment = xlCenter

MsgBox «Добавим к ячейкам диапазона A1:B3 границы»

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

MsgBox «Сделаем границы ячеек в диапазоне A1:B3 двойными»

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

MsgBox «Очистим ячейки диапазона A1:B3 от заливки, выравнивания, границ и содержимого»

Range(«A1:B3»).Clear

MsgBox «Присвоим высоте второй строки высоту первой, а ширине второго столбца — ширину первого»

Range(«A2»).RowHeight = Range(«A1»).RowHeight

Range(«B1»).ColumnWidth = Range(«A1»).ColumnWidth

MsgBox «Демонстрация форматирования ячеек закончена!»

End Sub

Вычисления в ячейках (свойство Value)

Запись двух чисел в ячейки, вычисление их произведения, вставка в ячейку формулы, очистка ячеек.

Обратите внимание, что разделителем дробной части у чисел в VBA Excel является точка, а не запятая.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

Sub Primer2()

MsgBox «Запишем в ячейку A1 число 25.3, а в ячейку B1 — число 34.42»

Range(«A1»).Value = 25.3

Range(«B1»).Value = 34.42

MsgBox «Запишем в ячейку C1 произведение чисел, содержащихся в ячейках A1 и B1»

Range(«C1»).Value = Range(«A1»).Value * Range(«B1»).Value

MsgBox «Запишем в ячейку D1 формулу, которая перемножает числа в ячейках A1 и B1»

Range(«D1»).Value = «=A1*B1»

MsgBox «Заменим содержимое ячеек A1 и B1 на числа 6.258 и 54.1, а также активируем ячейку D1»

Range(«A1»).Value = 6.258

Range(«B1»).Value = 54.1

Range(«D1»).Activate

MsgBox «Мы видим, что в ячейке D1 произведение изменилось, а в строке состояния отображается формула; « _

& «следующим шагом очищаем задействованные ячейки»

Range(«A1:D1»).Clear

MsgBox «Демонстрация вычислений в ячейках завершена!»

End Sub

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

Различие свойств Text, Value и Value2

Построение с помощью кода VBA Excel таблицы с результатами сравнения того, как свойства Text, Value и Value2 возвращают число, дату и текст.

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

46

47

48

49

50

51

52

53

54

55

56

Sub Primer3()

‘Присваиваем ячейкам всей таблицы общий формат на тот

‘случай, если формат отдельных ячеек ранее менялся

Range(«A1:E4»).NumberFormat = «General»

‘добавляем сетку (границы ячеек)

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

‘Создаем строку заголовков

Range(«A1») = «Значение»

Range(«B1») = «Код формата» ‘формат соседней ячейки в столбце A

Range(«C1») = «Свойство Text»

Range(«D1») = «Свойство Value»

Range(«E1») = «Свойство Value2»

‘Назначаем строке заголовков жирный шрифт

Range(«A1:E1»).Font.Bold = True

‘Задаем форматы ячейкам A2, A3 и A4

‘Ячейка A2 — числовой формат с разделителем триад и двумя знаками после запятой

‘Ячейка A3 — формат даты «ДД.ММ.ГГГГ»

‘Ячейка A4 — текстовый формат

Range(«A2»).NumberFormat = «# ##0.00»

Range(«A3»).NumberFormat = «dd.mm.yyyy»

Range(«A4»).NumberFormat = «@»

‘Заполняем ячейки A2, A3 и A4 значениями

Range(«A2») = 2362.4568

Range(«A3») = CDate(«01.01.2021»)

‘Функция CDate преобразует текстовый аргумент в формат даты

Range(«A4») = «Озеро Байкал»

‘Заполняем ячейки B2, B3 и B4 кодами форматов соседних ячеек в столбце A

Range(«B2») = Range(«A2»).NumberFormat

Range(«B3») = Range(«A3»).NumberFormat

Range(«B4») = Range(«A4»).NumberFormat

‘Присваиваем ячейкам C2-C4 значения свойств Text ячеек A2-A4

Range(«C2») = Range(«A2»).Text

Range(«C3») = Range(«A3»).Text

Range(«C4») = Range(«A4»).Text

‘Присваиваем ячейкам D2-D4 значения свойств Value ячеек A2-A4

Range(«D2») = Range(«A2»).Value

Range(«D3») = Range(«A3»).Value

Range(«D4») = Range(«A4»).Value

‘Присваиваем ячейкам E2-E4 значения свойств Value2 ячеек A2-A4

Range(«E2») = Range(«A2»).Value2

Range(«E3») = Range(«A3»).Value2

Range(«E4») = Range(«A4»).Value2

‘Применяем к таблице автоподбор ширины столбцов

Range(«A1:E4»).EntireColumn.AutoFit

End Sub

Результат работы кода:

Сравнение свойств ячейки Text, Value и Value2

В таблице наглядно видна разница между свойствами Text, Value и Value2 при применении их к ячейкам с отформатированным числом и датой. Свойство Text еще отличается от Value и Value2 тем, что оно предназначено только для чтения.


Понравилась статья? Поделить с друзьями:
  • Vba form listbox excel vba
  • Vba for word tables
  • Vba for excel for mac
  • Vba for excel exit sub
  • Vba for excel clear cells