No.1
Excel数据有多种格式,编程过程中,如果对数据格式分辨不清,那么带来的麻烦,真的无法言语。
数据格式分类大体有下面几类:
"数字", "货币", "负数", "文本","日期","时间","分数","百分"等等。
本节主要介绍如下几类:
"数字", "货币", "负数", "文本"
同样,对于设置数据格式针对的是某一个单元格区域进行,所以,要用到单元格区域对象Range。
Range对象下面的NumberFormat属性进行设置。
如下图介绍:
此属性可以定义单元格的数据格式。
Excel中有一些默认的格式,用一些字符来表示,如"General"为常规格式,"@"为文本格式,"#34;为货币格式等等。
No.2
应用方法
Dim cell As Range
Set cell = ActiveSheet.Range("A2:F2")
cell.NumberFormat = "$#,##0.00_);[Red]($#,##0.00);0.00;@"
分别用如下代码表示数据格式:
- 数字 #,##0.00_)
- 货币 $#,##0.00_)
- 负数 [Red]($#,##0.00)
- 文本 @
上述代码是Excel自定义的文本字符,"#"号表示n位数字,一个“0”代表一位数字,[Red]表示数据颜色为红色,字符"@"代表文本。
No.3
下面用一个实例进行演示:
本例单元按钮可自动生成一些数据列表,根据不同的表头,可显示不同的数据类型。
仔细看数据的布局和显示方式,可以分辨出数据之间的不同之处。
按钮代码:
Private Sub ShowNumberFormat()
On Error Resume Next
Application.ScreenUpdating = False
Dim Fname'定义表头数组
Fname = Array("格式名称", "原数据", "数字", "货币", "负数", "文本")
Dim cell As Range, xcell As Range
Set cell = ActiveSheet.Range("A2:F2")
cell.Value = Fname'设置表头
Set cell = ActiveSheet.Range("B3:B15")'定义数据区域
With cell
.Clear
.RowHeight = 20
.EntireRow.Borders.Item(xlEdgeBottom).LineStyle = 1
.EntireRow.Interior.Color = RGB(21, 221, 222)
With .Font
.Size = 12
.Name = "微软雅黑"
End With
End With
For Each xcell In cell
With xcell
.Value = VBA.Int((9999.99 - 99 + 1) * VBA.Rnd + 99)'随机生成数据
With .Offset(0, 1)
.Value = .Offset(0, -1).Value
.NumberFormat = "#,##0.00_)" '数字格式
End With
With .Offset(0, 2)
.Value = .Offset(0, -2).Value
.NumberFormat = "$#,##0.00_)" '货币格式
End With
With .Offset(0, 3)
.Value = .Offset(0, -3).Value
.NumberFormat = "[Red]($#,##0.00)" '负数货币格式
End With
With .Offset(0, 4)
.Value = .Offset(0, -4).Value
.NumberFormat = "@" '文本格式
End With
End With
Next xcell
Set xcell = Nothing
Set cell = Nothing
Application.ScreenUpdating = True
End Sub
No.4
关键代码如下四行。
.NumberFormat = "#,##0.00_)" '数字格式
.NumberFormat = "$#,##0.00_)" '货币格式
.NumberFormat = "[Red]($#,##0.00)" '负数货币格式
.NumberFormat = "@" '文本格式
其实在实际应用中,可以把不同的格式代码写到一起使用。
如:
.NumberFormat = "$#,##0.00_);[Red]($#,##0.00);0.00;@"
不同的数据格式标识之间用";"隔开。
其它格式,"日期","时间","分数","百分"等等,在另外一篇进行介绍。
欢迎关注、收藏
---END---