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
Below is a Sub that is being used to format all cells as text in the spreadsheet starting with worksheet3 onwards. As you’ll see there’s a line in bold that I will most likely need to change. One of the purposes of the line is to keep the values of the Column1 («Client ID») intact because in every sheet it consists ‘00001’ values that converted with this code would change to ‘1’. That’s wrong. Important thing is that Column1 in every worksheet always contains the same ‘00001’ values.
Sub formatAllCellsAsText()
Dim wsTemp As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Dim Cell As Range
For sht = 3 To Worksheets.Count
Set wsTemp = Sheets(sht)
Set StartCell = wsTemp.Range("A4")
LastRow = wsTemp.Range("A4").CurrentRegion.Rows.Count
LastColumn = wsTemp.Range("A4").CurrentRegion.Columns.Count
For Each Cell In wsTemp.Range(StartCell, wsTemp.Cells(LastRow, LastColumn)).Cells
If Not IsEmpty(Cell.Value) And IsNumeric(Cell.Value)
And InStr(wsTemp.Cells(1, Cell.Column), "Client ID") <= 0 Then
Dim Temp As Double
Temp = Cell.Value
Cell.ClearContents
Cell.NumberFormat = "@"
Cell.Value = CStr(Temp)
End If
Next
Next sht
End Sub
Now my problem is that in one worksheet there’s Column6 («Value») that I want to preseve 000s in front of a number. When I change the line to the following my macro still removes preceding 000s from the Column6 values. I guess the condition is not as straightforward as I have thought.
If Not IsEmpty(Cell.Value) And IsNumeric(Cell.Value) And
InStr(wsTemp.Cells(1, Cell.Column), "Client ID") <= 0 And
InStr(wsTemp.Cells(6, Cell.Column), "Value") <= 0 Then
Any suggestions?
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
By formatting cells and ranges you can give your worksheets a better look. Formatting applies to the following:
- The number format: Numeric, Date, Scientific …
- Text Alignment: Horizontal, Vertical, Orientation …
- Text Control: Wrap Text, Shrink to fit, Merge Cells …
- Text Direction
- Font Type: Calibri, Times new Roman …
- Font Style: Regular, Italic …
- Font Size: 8, 9, 10 …
- Font Color
- Font Effects: Strike through, Superscript …
- Borders: Style, Color, …
- Fill: Color, Pattern …
- Protection: Locked, Hidden
- …
As you can see there are a lot of different formatting options in excel. Listing all of them along with their syntax and examples would require an entire book. Fortunately excel has provided a tool for figuring out the syntax of the different formatting options, the macro recorder. Using the macro recorder you can figure out how to apply different formattings to ranges.
Jump To:
- Formatting Cells and the Macro Recorder
- Formatting Cell Borders
- Formatting Cell Protection
- Formatting Cell Font
- Formatting Cell Alignment
- Changing Cells Number Format
–
Formatting Cells and the Macro Recorder:
Below I will explain how to use macro recorder to figure out the required syntax for a specific type of formatting:
Step 1: In the developer tab click on Record Macro button:
Step 2: Click Ok:
Step 3: Apply the desired formatting to a range of cells. In this example I will change the color of the range to yellow and a apply a thick border to the exterior and interior sides of the range:
Step 4: Stop the macro recorder
Step 6: Open the visual basic editor. On the project window you will see a new folder which has been created called “Modules”. In this folder there will be a new file “Macro1”. By clicking on it you will see the generated Code:
For this example the code shown below has been generated:
Sub Macro1()
'
' Macro1 Macro
'
'
Range("I11:P16").Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
Remember that the macro recorder, records your every action. So if you have the macro recorder on and you start doing random things, the final generated code will become very long. So when you are trying to record a macro try to avoid any unnecessary actions. The first line of code you see is:
Range("I11:P16").Select
You will have to replace “I11:P16” with the range you are trying to modify . Also instead of using the select command you could directly use the range object:
Range("I11:P16").Borders(xlDiagonalDown).LineStyle = xlNone
Range("I11:P16").Borders(xlDiagonalUp).LineStyle = xlNone
With Range("I11:P16").Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
I have brought some examples below.
–
Formatting Cell Borders:
The following example creates a border on the left edge of cell A1. The pattern is continuous and thick
With Range("A1").Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThick
End With
I have covered this topic in detail in the article below:
- Excel VBA, Borders
–
Formatting Cell Protection:
The following example locks and hides cells A1:
Range("A1").Locked = True
Range("A1").FormulaHidden = True
–
Formatting Cell Font:
The following code changes the font in cell A1 to arial, bold with size 9, applies strike through and single line underline formatting:
With Range("A1").Font
'font type
.Name = "Arial"
'font style
.FontStyle = "Bold"
'font size
.Size = 9
'uncheck strikethrough
.Strikethrough = True
'uncheck superscript
.Superscript = False
'uncheck subscript
.Subscript = False
.OutlineFont = False
.Shadow = False
'select single line underscript
.Underline = xlUnderlineStyleSingle
'set color to yellow
.Color = 65535
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
For more information about formatting font properties please see the article below:
- VBA, Excel Font Formatting
–
Formatting Cell Alignment:
The following code sets the horizontal alignment of cell A1 to left, justifies its vertices alignment. Checks the wrap text and merge cell options and applies a -45 degree orientation:
With Range("A1")
'set the horizontal alignement to left
.HorizontalAlignment = xlLeft
'set the verticle alignment to justify
.VerticalAlignment = xlJustify
'check the wrap text option
.WrapText = True
'apply a -45 deg orientation
.Orientation = -45
'check the merge cell option
.MergeCells = True
End With
For more information about cell alignment please see the article below:
- VBA Excel, Alignment
–
Changing Cells Number Format:
The following code changes cells A1’s number format to a date with the mm/dd/yy format:
Range("A1").NumberFormat = "mm/dd/yy;@"
See Also:
- VBA Excel, Font Formatting.
- VBA Excel, Alignment
- Excel VBA, Borders
If you need assistance with your code, or you are looking to hire a VBA programmer feel free to contact me. Also please visit my website www.software-solutions-online.com
Tagged with: Border, Cell Border, Cell Color, Cells, Color, Excel, Fill Color, Font, Font Color, Font Style, Formatting, Macro Recorder, Number Format, Ranges, Scientific, VBA
Содержание
- VBA Format Cells
- Formatting Cells
- AddIndent
- Borders
- FormulaHidden
- HorizontalAlignment
- VBA Coding Made Easy
- IndentLevel
- Interior
- Locked
- MergeCells
- NumberFormat
- NumberFormatLocal
- Orientation
- Parent
- ShrinkToFit
- VerticalAlignment
- WrapText
- VBA Code Examples Add-in
- Formatting a Range of Cells In Excel VBA
- Formatting Cells Number
- General
- Number
- Currency
- Accounting
- Percentage
- Fraction
- Scientific
- Special
- Custom
- Formatting Cells Alignment
- Text Alignment
- Horizontal
- Vertical
- Text Control
- Wrap Text
- Shrink To Fit
- Merge Cells
- Right-to-left
- Text direction
- Orientation
- Font Name
- Font Style
- Font Size
- Underline
- Font Color
- Font Effects
- Strikethrough
- Subscript
- Superscript
- Border
- Border Index
- Line Style
- Line Thickness
- Line Color
- Pattern Style
- Protection
- Locking Cells
- Hiding Formulas
- How do I get the format of a cell in VBA
- 4 Answers 4
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
VBA Format Cells
In this Article
This tutorial will demonstrate how to format cells using VBA.
Formatting Cells
There are many formatting properties that can be set for a (range of) cells like this:
Let’s see them in alphabetical order:
AddIndent
By setting the value of this property to True the text will be automatically indented when the text alignment in the cell is set, either horizontally or vertically, to equal distribution (see HorizontalAlignment and VerticalAlignment).
Borders
You can set the border format of a cell. See here for more information about borders.
As an example you can set a red dashed line around cell B2 on Sheet 1 like this:
You can adjust the cell’s font format by setting the font name, style, size, color, adding underlines and or effects (strikethrough, sub- or superscript). See here for more information about cell fonts.
Here are some examples:
FormulaHidden
This property returns or sets a variant value that indicates if the formula will be hidden when the worksheet is protected. For example:
HorizontalAlignment
This property cell format property returns or sets a variant value that represents the horizontal alignment for the specified object. Returned or set constants can be: xlGeneral, xlCenter, xlDistributed, xlJustify, xlLeft, xlRight, xlFill, xlCenterAcrossSelection. For example:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
IndentLevel
It returns or sets an integer value between 0 and 15 that represents the indent level for the cell or range.
Interior
You can set or get returned information about the cell’s interior: its Color, ColorIndex, Pattern, PatternColor, PatternColorIndex, PatternThemeColor, PatternTintAndShade, ThemeColor, TintAndShade, like this:
Locked
This property returns True if the cell or range is locked, False if the object can be modified when the sheet is protected, or Null if the specified range contains both locked and unlocked cells. It can be used also for locking or unlocking cells.
This example unlocks cells A1:B2 on Sheet1 so that they can be modified when the sheet is protected.
MergeCells
Set this property to True if you need to merge a range. Its value gets True if a specified range contains merged cells. For example, if you need to merge the range of C5:D7, you can use this code:
NumberFormat
You can set the number format within the cell(s) to General, Number, Currency, Accounting, Date, Time, Percentage, Fraction, Scientific, Text, Special and Custom.
Here are the examples of scientific and percentage number formats:
NumberFormatLocal
This property returns or sets a variant value that represents the format code for the object as a string in the language of the user.
Orientation
You can set (or get returned) the text orientation within the cell(s) by this property. Its value can be one of these constants: xlDownward, xlHorizontal, xlUpward, xlVertical or an integer value from –90 to 90 degrees.
Parent
This is a read-only property that returns the parent object of a specified object.
ShrinkToFit
This property returns or sets a variant value that indicates if text automatically shrinks to fit in the available column width.
VerticalAlignment
This property cell format property returns or sets a variant value that represents the vertical alignment for the specified object. Returned or set constants can be: xlCenter, xlDistributed, xlJustify, xlBottom, xlTop. For example:
WrapText
This property returns True if text is wrapped in all cells within the specified range, False if text is not wrapped in all cells within the specified range, or Null if the specified range contains some cells that wrap text and other cells that don’t.
For example, if you have this range of cells:
this code below will return Null in the Immediate Window:
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Formatting a Range of Cells In Excel VBA
Formatting Cells Number
General
Number
Currency
Accounting
Percentage
Fraction
Scientific
Special
Custom
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.
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.
Text Control
Wrap Text
This example formats cell A1 so that the text wraps within the cell.
Shrink To Fit
This example causes text in row one to automatically shrink to fit in the available column width.
Merge Cells
This example merge range A1:A4 to a large one.
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).
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.
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.
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.
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.
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).
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:
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).
The following code sets the font color of cell A1 to 0 (Black).
The following code sets the font color of cell A1 to RGB(0, 0, 0) (Black).
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.
Subscript
True if the font is formatted as subscript. False by default.
The following code sets the font of cell A1 to Subscript.
Superscript
True if the font is formatted as superscript; False by default.
The following code sets the font of cell A1 to Superscript.
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.
The following code example removes the border on the bottom edge of cell A1.
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).
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.
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.
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.
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.
Источник
How do I get the format of a cell in VBA
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
4 Answers 4
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?
Try using the following in VBA:
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.
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.
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.
Linked
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43331
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Change Font size
ActiveCell.Font.Size = 14
5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!
Embolden font
Selection.Font.Bold = True
Italicise font
Selection.Font.Italic = True
Underline font
Selection.Font.Underline = True
Font colour
5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!
Selection.Font.Color = vbRed
Also: vbBlack, vbBlue, vbCyan, vbGreen, vbMagenta, vbWhite,vbYellow
Selection.Font.Color = rgbBlueViolet
NB. Use CTRL SPACE to show the intellisense list of rgb colours
Selection.Font.Color = RGB(10, 201, 88)
ActiveCell.Font.ThemeColor = xlThemeColorAccent2
Selection.Font.ColorIndex = 49
This table shows the index number for colours in the default colour palette.
Background Colour of Cell/s
See font colour above for different ways of specifying colour.
Selection.Interior.Color = vbRed
Cell Borders
5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!
See font colour above for different ways of specifying colour.
Selection.Borders.Color = vbBlue
You can also specify properties such as weight and line style
With Selection.Borders .Color = vbBlue .Weight = xlMedium .LineStyle = xlDash End With
Cell Alignment
Selection.HorizontalAlignment = xlCenter
Selection.VerticalAlignment = xlTop
To merge and center
Range("A1:E1").Merge Range("A1").HorizontalAlignment = xlCenter
Number Format
ActiveCell.NumberFormat = "£#,##0.00;[Red]-£#,##0.00"
ActiveCell.NumberFormat = "0%"
ActiveCell.NumberFormat = "dd/mm/yyyy"
Use the custom format codes available in Excel’s Format | Cells dialog box.
-
04-21-2005, 11:06 AM
#1
Formatting all cells or sheet
Although I’m not familair with the Excel object libarary, I am familiar with
VBA. How can I format the whole sheet to use Text as the cell formatting, as
opposed to General, the default?Me.Cells.Format…?
Thanks,
Steve
-
04-21-2005, 01:06 PM
#2
Re: Formatting all cells or sheet
Activesheet.Cells.Numberformat = «@»
—
HTH
RP
(remove nothere from the email address if mailing direct)«Steve Schroeder» <sschroeder@somewhere.com> wrote in message
news:urFX8znRFHA.2384@tk2msftngp13.phx.gbl…
> Although I’m not familair with the Excel object libarary, I am familiar
with
> VBA. How can I format the whole sheet to use Text as the cell formatting,
as
> opposed to General, the default?
>
> Me.Cells.Format…?
>
> Thanks,
>
> Steve
>
>
-
04-21-2005, 01:06 PM
#3
RE: Formatting all cells or sheet
Activesheet.cells.numberformat=»@»
«Steve Schroeder» wrote:
> Although I’m not familair with the Excel object libarary, I am familiar with
> VBA. How can I format the whole sheet to use Text as the cell formatting, as
> opposed to General, the default?
>
> Me.Cells.Format…?
>
> Thanks,
>
> Steve
>
>
>
-
04-22-2005, 11:06 AM
#4
Re: Formatting all cells or sheet
Thanks both of you for your help, that did appear to work. As is usually the
case, the situation is a bit more complicated.Becase the column I am formatting contains a string value of:
12929.00000001 (case number, text, not an 8 decimal place number)
Even formatting it to text still leaves it 12929, at least visually. If you
pretend to edit the cell, then move to another, it then appears as wished,
the full string. I should also mention that this data is coming in from an
ASP.Net web page. I actually tried to add the formatting in the VBScript
code, but only got an error, incidently not the line I add,
i.e.Activesheet.Cells.Numberformat = «@»The error is: Invalid Procedure Call or argument, and it happens on:
HTMLProjectItems(«Sheet1»).Text = sHTML. Here is the VBScript code I’m
using. Any thoughts or ideas would be greatly appreciated. Thanks!Sub cmdExcel_onclick()
Dim sHTML
sHTML = window.document.forms(0).children(4).outerhtml
Dim oXL, oBook
Set oXL = CreateObject(«Excel.Application»)
Set oBook = oXL.Workbooks.Add
oXL.Sheets(«Sheet1»).Cells.NumberFormat = «@»
oBook.HTMLProject.HTMLProjectItems(«Sheet1»).Text = sHTML
oBook.HTMLProject.RefreshDocument
oXL.Visible = true
oXL.UserControl = true
End Sub«Steve Schroeder» <sschroeder@somewhere.com> wrote in message
news:urFX8znRFHA.2384@tk2msftngp13.phx.gbl…
> Although I’m not familair with the Excel object libarary, I am familiar
with
> VBA. How can I format the whole sheet to use Text as the cell formatting,
as
> opposed to General, the default?
>
> Me.Cells.Format…?
>
> Thanks,
>
> Steve
>
>
-
04-22-2005, 01:06 PM
#5
Re: Formatting all cells or sheet
Ok, well here’s what I did, although it isn’t a perfect solution:
oXL.Sheets(«Sheet1»).Columns(1).Cells.NumberFormat = «#####.########»
oXL.Sheets(«Sheet1»).Columns(1).Cells.HorizontalAlignment = -4131«Steve Schroeder» <sschroeder@somewhere.com> wrote in message
news:eXkWcS0RFHA.3716@TK2MSFTNGP14.phx.gbl…
> Thanks both of you for your help, that did appear to work. As is usually
the
> case, the situation is a bit more complicated.
>
> Becase the column I am formatting contains a string value of:
>
> 12929.00000001 (case number, text, not an 8 decimal place number)
>
> Even formatting it to text still leaves it 12929, at least visually. If
you
> pretend to edit the cell, then move to another, it then appears as wished,
> the full string. I should also mention that this data is coming in from an
> ASP.Net web page. I actually tried to add the formatting in the VBScript
> code, but only got an error, incidently not the line I add,
> i.e.Activesheet.Cells.Numberformat = «@»
>
> The error is: Invalid Procedure Call or argument, and it happens on:
> HTMLProjectItems(«Sheet1»).Text = sHTML. Here is the VBScript code I’m
> using. Any thoughts or ideas would be greatly appreciated. Thanks!
>
> Sub cmdExcel_onclick()
> Dim sHTML
> sHTML = window.document.forms(0).children(4).outerhtml
> Dim oXL, oBook
> Set oXL = CreateObject(«Excel.Application»)
> Set oBook = oXL.Workbooks.Add
> oXL.Sheets(«Sheet1»).Cells.NumberFormat = «@»
> oBook.HTMLProject.HTMLProjectItems(«Sheet1»).Text = sHTML
> oBook.HTMLProject.RefreshDocument
> oXL.Visible = true
> oXL.UserControl = true
> End Sub
>
>
>
> «Steve Schroeder» <sschroeder@somewhere.com> wrote in message
> news:urFX8znRFHA.2384@tk2msftngp13.phx.gbl…
> > Although I’m not familair with the Excel object libarary, I am familiar
> with
> > VBA. How can I format the whole sheet to use Text as the cell
formatting,
> as
> > opposed to General, the default?
> >
> > Me.Cells.Format…?
> >
> > Thanks,
> >
> > Steve
> >
> >
>
>