Sunday, March 1, 2009

Number Formatting in Excel VBA Macro

Number formatting controls how numbers on cells are displayed, it has no effect on cells that contain text. In Microsoft Excel, if we want to apply number formatting we can use Format Cells dialog box. To format numbers in VBA macro we can use the NumberFormat property. Following are some number formatting codes to format numbers.

Number Formatting Codes
Character Meaning Code example Format example
# Significant digit ##.# 10.78 displays as 10.9
0 Nonsignificant 0 #.00 5.4 displays as 5.40
. Decimal point ##.## 14.55 displays as 14.55
$ Currency symbol $#.## 56.78 displays as $56.78
% Percent symbol #.#% 0.075 displays as 7.5%
, Thousands separator #,### 123000 displays as 123,000


Here is the example VBA code to display numbers with no commas or special characters, and no decimal places:

Sub NumFormat()
Range("A1").NumberFormat = "0"
End Sub

We can display positive and negative numbers differently. Following number format code will display negative numbers in red color.

#.##;[Red]#.##

To specify a display color, include the color name enclosed in square brackets at the start the format code. The available color names are:
  • Black
  • Blue
  • Cyan
  • Green
  • Magenta
  • Red
  • White
  • Yellow

---
If you like posts in this blog, you can to support me :)