[英]Excel VBA, how to achieve this formatting? Nmbr with commas and rounding to 2 decimal
所以如果我们有一个数字 99999.23412343 我希望它显示 99,999.23 换句话说,有一个千位分隔符逗号和 2 个小数位四舍五入。
我在这里有这段代码,它使值看起来像那样,但实际上并没有四舍五入。 有没有办法为此计算添加舍入或使值本身为 2 位小数?
Sub roundcode()
Columns("G:G").Select
Selection.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
End Sub
我不知道该格式应该做什么。 如果您想要带有两位小数的千位,只需使用:
Columns("G:G").NumberFormat = "#,000.00"
无需Select
进行格式化。 有关所有数字、时间、日期格式的良好参考,请使用以下链接https://peltiertech.com/Excel/NumberFormats.html
这将同时应用实际舍入和格式舍入:
Sub roundd()
Dim rng As Range, cell As Range
Set rng = Intersect(Columns("G:G"), ActiveSheet.UsedRange)
With Application.WorksheetFunction
For Each cell In rng
If cell.HasFormula Then
txt = "(" & Mid(cell.Formula, 2) & ")"
cell.Formula = "=ROUND(" & txt & ",2)"
Else
cell.Value = .Round(cell.Value, 2)
End If
Next cell
End With
rng.NumberFormat = "#,000.00"
End Sub
它将处理公式和常量。
编辑#1:
为避免第一行,请替换:
Columns("G:G")
有类似的东西:
Range("G2:G999999")
编辑#2:
试试这个:
Sub roundd()
Dim rng As Range, cell As Range
Set rng = Intersect(Range("G2:G999999"), ActiveSheet.UsedRange)
With Application.WorksheetFunction
For Each cell In rng
If cell.HasFormula Then
txt = "(" & Mid(cell.Formula, 2) & ")"
cell.Formula = "=ROUND(" & txt & ",2)"
Else
If cell.Value <> "" Then
cell.Value = .Round(cell.Value, 2)
End If
End If
Next cell
End With
rng.NumberFormat = "#,000.00"
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.