【问题标题】:How to format to two decimal places only if decimals required仅在需要小数时如何格式化为两位小数
【发布时间】:2022-09-26 14:24:54
【问题描述】:

我有一些列,其中数据可以是整数或长小数(例如 0.6666667)。

我想将小数格式化为两位小数,但我不希望整数显示 .00 小数。

我在其他地方看到了一个类似的问题,这个代码作为答案,但这会在整数后留下一个小数点(5.而不是5):

Range(\"Q8:Q500\").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
    \"=(Q8-INT(Q8))>0\"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
 Selection.NumberFormat = \"[=0]0;.##\"
Selection.FormatConditions(1).StopIfTrue = False

我尝试了一个 if 语句来根据是否存在小数点来格式化:

For Each Cell In Columns(\"Q\")
    If Cell.Value = \"*.*\" Then
        Cell.NumberFormat = \"0.00\"
    Else
        Cell.NumberFormat = \"General\"
    End If
Next

我宁愿不添加列,因为文件已经很大。

  • 代替If Cell.Value = \"*.*\" Then,与Like 运算符比较:If Cell.Value Like \"*.*\" Then
  • IF Round(Cell.Value,2) <> int(cell.value) Then

标签: excel vba


【解决方案1】:

我会使用这样的子 - 在应用它检查错误或文本的数字格式之前 - 并退出。这样您就可以确定只处理数字。

Sub reformatNumber(c As Range)

If IsError(c.value) Then Exit Sub
If Not IsNumeric(c.Value2) Then Exit Sub

If Int(c.Value2) <> c.Value2 Then
    c.NumberFormat = "0.00"
Else
    c.NumberFormat = "0"
End If

End Sub

你可以像这样测试它:

Sub test_reformat()
Dim c As Range
For Each c In Selection
    reformatNumber c
Next
End Sub

【讨论】:

    【解决方案2】:

    使用条件格式。 它的工作示例:

    选择范围,将其格式化为“0”,使用自定义公式“=A1<>round(A1,0)”添加条件格式,数字格式为“0.00”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多