首页 > 解决方案 > Excel在数字中显示零而没有错误

问题描述

在 excel VBA 中,如何显示以下数字而不在单元格中生成“数字存储为文本”错误?

1.0
1.1
1.2
.
.
1.99
1.100
1.101
1.102
.
.
1.20
1.21
1.22
.
.
etc...

标签: excelvbanumbersformat

解决方案


只需跟踪需要显示的小数位数。例如:

Sub marine()
    Dim s As String, i As Long, a
    s = "1.0,1.1,1.2,1.99,1.100,1.101,1.102,1.20,1.21,1.22"
    arr = Split(s, ",")

    i = 1
    For Each a In arr
        With Cells(i, 1)
            .Value = a
            brr = Split(a, ".")
            .NumberFormat = "0." & Application.Rept("0", Len(brr(1)))
        End With
        i = i + 1
    Next a
End Sub

在此处输入图像描述

这是基于一个奇怪的事实,即如果 VBA 将类似数字的字符串放入单元格中,Excel 会将其转换为数字:

Sub demo()
    Dim s As String
    s = "1.230"
    Range("A1").Value = s
End Sub

编辑#1:

另一方面,如果您想输入看起来像数字的文本,但要避免引发错误标志,那么:

Sub Macro1()
    Application.ErrorCheckingOptions.NumberAsText = False
End Sub

推荐阅读