Excel VBA,如何实现这种格式化?带逗号和四舍五入到小数点后两位的数字

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格式化。对于所有数字、时间、日期格式的良好参考,请使用以下 link 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