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.
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
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 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
All examples ypu can find in this file:
Excercises (You can enter the solution in a comment)
- 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 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:
- xlDiagonalDown (Border running from the upper left-hand corner to the lower right of each cell in the range).
- xlDiagonalUp (Border running from the lower left-hand corner to the upper right of each cell in the range).
- xlEdgeBottom (Border at the bottom of the range).
- xlEdgeLeft (Border at the left-hand edge of the range).
- xlEdgeRight (Border at the right-hand edge of the range).
- xlEdgeTop (Border at the top of the range).
- xlInsideHorizontal (Horizontal borders for all cells in the range except borders on the outside of the range).
- 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:
- xlPatternAutomatic (Excel controls the pattern.)
- xlPatternChecker (Checkerboard.)
- xlPatternCrissCross (Criss-cross lines.)
- xlPatternDown (Dark diagonal lines running from the upper left to the lower right.)
- xlPatternGray16 (16% gray.)
- xlPatternGray25 (25% gray.)
- xlPatternGray50 (50% gray.)
- xlPatternGray75 (75% gray.)
- xlPatternGray8 (8% gray.)
- xlPatternGrid (Grid.)
- xlPatternHorizontal (Dark horizontal lines.)
- xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.)
- xlPatternLightHorizontal (Light horizontal lines.)
- xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.)
- xlPatternLightVertical (Light vertical bars.)
- xlPatternNone (No pattern.)
- xlPatternSemiGray75 (75% dark moiré.)
- xlPatternSolid (Solid color.)
- 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
When iterating through cells in a worksheet, how can I get what the format setting on the cell is? Because based on this, I would like to build a SQL statement to either add the single ticks or not to the value retreived
asked Mar 12, 2013 at 21:19
2
Sounds like you need the VarType() function. Vartype(Range("A1"))
OK, so you don’t want to know the format setting for the cell, but whether the value is numeric.
Can you just call IsNumeric(Range("A1"))
and quote it if False
?
Based on your comment that some numbers are stored as text in the DB, you are not going to solve this by a simple formula. Can’t you just quote the values as you build your SQL statement?
answered Mar 12, 2013 at 21:25
mr_plummr_plum
2,4481 gold badge17 silver badges31 bronze badges
7
Try using the following in VBA:
Range("A1").NumberFormat = "0.00" 'Sets cell formatting to numeric with 2 decimals.
Range("A1").Formula = "=Text(6, " & """0.00""" & ")" 'Looks like a number _
' but is really text.
Debug.Print WorksheetFunction.IsNumber(Range("A1")) 'Prints False
Range("A1").Value = 6 'Puts number into the cell, which also looks like 6.00
Debug.Print WorksheetFunction.IsNumber(Range("A1")) 'Prints True
This should tell you if the value is really text or really a number, regardless of the cell’s formatting properties.
The key is that the intrinsic Excel IsNumber() function works better for this purpose than the VBA function IsNumeric. IsNumber() tells you whether the cell’s value is a number, whereas IsNumeric only tells you if the cell is formatted for numeric values.
answered Jun 13, 2018 at 1:31
I don’t think there’s any property of a cell that indicates whether the cell actually contains a numeric value, although VarType()
might help, it gets tricky because Excel will allow a number-formatted cell to contain string, and a text formatted cell to contain numeric values, without overriding the NumberFormat
property.
In any case you likely need some independent test to figure out whether a cell IsNumeric (or other criteria) AND whether its NumberFormat
is among an enumerated list which you can define.
Sub numFormat()
Dim cl As Range
Dim numFormat As String
Dim isNumber As Boolean
For Each cl In Range("A1")
numFormat = cl.NumberFormat
isNumber = IsNumeric(Trim(cl.Value))
Select Case numFormat
Case "General", "0", "0.0", "0.00" ' <--- modify as needed to account for other formats, etc.
If isNumber Then
Debug.Print cl.Address & " formatted as " & numFormat
End If
Case Else
'ignore all other cases
End Select
Next
End Sub
answered Mar 13, 2013 at 3:25
David ZemensDavid Zemens
52.8k11 gold badges79 silver badges129 bronze badges
I don’t think the format of the cell is the important thing. Rather, it’s the data type of the field in your database. If you have the string ‘foobar’ in a cell and you create an INSERT INTO sql statement that attempts to put that into a Long Integer field, it’s going to fail regardless of tickmarks.
Conversely, if a cell contains a numeric value (like 100) that needs to go into a VARCHAR field, it will need tickmarks (like ‘100’).
If you’re using ADO, check the Type property of the Field object to determine the data type. Use this list http://support.microsoft.com/kb/193947 to see what the types are. Then set up the SQL statement according to the field type.
answered Mar 13, 2013 at 13:47
Dick KusleikaDick Kusleika
32.5k4 gold badges51 silver badges73 bronze badges
Как выбрать и изменить форматирование диапазона
На чтение 3 мин. Просмотров 2.8k.
Что делает макрос: Этот простой макрос выбирает диапазон D5: D16 и форматирует его.
Содержание
- Как макрос работает
- Код макроса
- Как этот код работает
- Код макроса
- Как этот код работает
- Код макроса
- Как использовать
Как макрос работает
В этом макросе определяется диапазон для выбора с помощью объекта Range.
Код макроса
Sub VibratDiapazon() 'Выбор диапазона Range("D5:D16").Select End Sub
После того, как выбран диапазон ячеек, вы можете использовать любые свойства Range, манипулируя ячейками. Мы изменили этот макрос, чтобы диапазон желтого цвета преобразовался в формат числа и стал выделенным жирным шрифтом.
Sub IzmenitFormat() 'Выбор диапазона Range("D5:D16").Select 'Преобразование в формат числа Selection.NumberFormat = "#,##0" 'Жирный шрифт Selection.Font.Bold = True 'Заливка желтым цветом Selection.Interior.ColorIndex = 36 End Sub
Вам не нужно запоминать все свойства объекта ячейки для того, чтобы манипулировать ими. Вы можете просто записать макрос, выполните форматирование, а затем посмотреть на код, который написал Excel. После того, как вы увидели, что синтаксис правильный, вы можете применить его по мере необходимости. Многие программисты Excel начинают обучение VBA с этого.
Вы заметили, что мы называем Selection много раз в предыдущем примере кода. Для того, чтобы написать более эффективный код, вы можете просто сослаться на диапазон, используя With … End With. Этот оператор говорит Excel, что любое действие, которое вы выполняете относится к объекту, который вы указали.
Обратите внимание, что этот макрос фактически не выбирает диапазон в первую очередь. Это ключевой момент. В макросе, мы можем работать с диапазоном, не выбирая его в первую очередь.
Sub IzmenitFormatWith() With Range("D5:D16") .NumberFormat = "#,##0" .Font.Bold = True .Interior.ColorIndex = 36 End With End Sub
Как этот код работает
Еще один способ, вы можете выбрать диапазон с помощью элемента ячейки объекта Range.
Адрес ячеек — это удобный способ выбора диапазонов через код. Он требует только позиции строк и столбцов в качестве параметров. Ячейка (5, 4) относится к строке 5, столбцу 4 (или ячейка D5).
Ячейки (16, 4) относится к строке 16, столбцу 4 (или ячейки D16). Если вы хотите выбрать диапазон ячеек, просто укажите два пункта в объект Range. Этот макрос выполняет один и тот же выбор диапазона D5:D16:
Код макроса
Sub IzmenitFormatRange() Range(Cells(5, 4), Cells(16, 4)).Select End Sub
Как этот код работает
Вот полный код форматирования с помощью позиций ячеек. Опять же, обратите внимание, что этот макрос фактически не меняет диапазон. Мы можем работать с диапазоном, не выделяя его.
Код макроса
Sub IzmenitFormat3() With Range(Cells(5, 4), Cells(16, 4)) .NumberFormat = "#,##0" .Font.Bold = True .Interior.ColorIndex = 36 End With End Sub
Как использовать
Для реализации такого рода макроса, вы можете скопировать и вставить его в стандартный модуль:
- Активируйте редактор Visual Basic, нажав ALT + F11 на клавиатуре.
- Щелкните правой кнопкой мыши имя проекта / рабочей книги в окне проекта.
- Выберите Insert➜Module.
- Введите или вставьте код в окно кода.
In this Article
- Formatting Cells
- AddIndent
- Borders
- Font
- FormulaHidden
- HorizontalAlignment
- IndentLevel
- Interior
- Locked
- MergeCells
- NumberFormat
- NumberFormatLocal
- Orientation
- Parent
- ShrinkToFit
- VerticalAlignment
- WrapText
This tutorial will demonstrate how to format cells using VBA.
Formatting Cells
There are many formatting properties that can be set for a (range of) cells like this:
Sub SetCellFormat()
With Worksheets("Sheet1").Range("B5:C7")
.HorizontalAlignment = xlHAlignDistributed
.AddIndent = True
.Font.FontStyle = "Italic"
.NumberFormat = "General"
.Interior.Color = RGB(128, 100, 250)
End With
End Sub
Let’s see them in alphabetical order:
AddIndent
By setting the value of this property to True the text will be automatically indented when the text alignment in the cell is set, either horizontally or vertically, to equal distribution (see HorizontalAlignment and VerticalAlignment).
With Worksheets("Sheet1").Range("A1")
.Orientation = xlVertical
.VerticalAlignment = xlVAlignDistributed
.AddIndent = True
End With
Borders
You can set the border format of a cell. See here for more information about borders.
As an example you can set a red dashed line around cell B2 on Sheet 1 like this:
Worksheets("Sheet1").Range("B2").BorderAround LineStyle:=xlDash, ColorIndex:=3
Font
You can adjust the cell’s font format by setting the font name, style, size, color, adding underlines and or effects (strikethrough, sub- or superscript). See here for more information about cell fonts.
Here are some examples:
With Range("A1:C5").Font
.Name = "Century"
.FontStyle = "Bold"
.Strikethrough = True
End With
FormulaHidden
This property returns or sets a variant value that indicates if the formula will be hidden when the worksheet is protected. For example:
Worksheets("Sheet1").Range("A1:B1").FormulaHidden = True
HorizontalAlignment
This property cell format property returns or sets a variant value that represents the horizontal alignment for the specified object. Returned or set constants can be: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight, xlFill, xlCenterAcrossSelection. For example:
Worksheets("Sheet1").Range("D3").HorizontalAlignment = xlRight
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
IndentLevel
It returns or sets an integer value between 0 and 15 that represents the indent level for the cell or range.
Worksheets("Sheet1").Range("A1").IndentLevel = 7
Interior
You can set or get returned information about the cell’s interior: its Color, ColorIndex, Pattern, PatternColor, PatternColorIndex, PatternThemeColor, PatternTintAndShade, ThemeColor, TintAndShade, like this:
If Not Range("A1").Interior.ThemeColor = ThemeColorLight2 Then
Range("A1").Interior.Pattern = xlPatternUp
End If
Locked
This property returns True if the cell or range is locked, False if the object can be modified when the sheet is protected, or Null if the specified range contains both locked and unlocked cells. It can be used also for locking or unlocking cells.
This example unlocks cells A1:B2 on Sheet1 so that they can be modified when the sheet is protected.
Worksheets("Sheet1").Range("A1:B2").Locked = False
Worksheets("Sheet1").Protect
VBA Programming | Code Generator does work for you!
MergeCells
Set this property to True if you need to merge a range. Its value gets True if a specified range contains merged cells. For example, if you need to merge the range of C5:D7, you can use this code:
Worksheets("Sheet1").Range("C5:D7").MergeCells = True
NumberFormat
You can set the number format within the cell(s) to General, Number, Currency, Accounting, Date, Time, Percentage, Fraction, Scientific, Text, Special and Custom.
Here are the examples of scientific and percentage number formats:
Range("A1").NumberFormat = "0.00E+00"
Range("B1").NumberFormat = "0.00%"
NumberFormatLocal
This property returns or sets a variant value that represents the format code for the object as a string in the language of the user.
Orientation
You can set (or get returned) the text orientation within the cell(s) by this property. Its value can be one of these constants: xlDownward, xlHorizontal, xlUpward, xlVertical or an integer value from –90 to 90 degrees.
Worksheets("Sheet1").Range("A1").Orientation = -60
Parent
This is a read-only property that returns the parent object of a specified object.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
ShrinkToFit
This property returns or sets a variant value that indicates if text automatically shrinks to fit in the available column width.
Worksheets("Sheet1").Range("A1").ShrinkToFit = True
VerticalAlignment
This property cell format property returns or sets a variant value that represents the vertical alignment for the specified object. Returned or set constants can be: xlCenter, xlDistributed, xlJustify, xlBottom, xlTop. For example:
Worksheets("Sheet1").Range("A1").VerticalAlignment = xlTop
WrapText
This property returns True if text is wrapped in all cells within the specified range, False if text is not wrapped in all cells within the specified range, or Null if the specified range contains some cells that wrap text and other cells that don’t.
For example, if you have this range of cells:
this code below will return Null in the Immediate Window:
?Worksheets("Sheet1").Range("A1:B1").WrapText