当我使用 "Format(string_variable, "###.#" 并且 string_variable 的值设置为 0.0 时,为什么 VBA 会引发 "type mismatch" 错误

Why does VBA raise a "type mismatch" error when I use "Format(string_variable, "###.#") and the value of the string_variable is set to 0.0

我的股票交易代码格式化价格变化(单一变量)以传输到我的单元格 phone 并限制无关紧要的数字的数量。当价格变化为零时,模块会引发 "Type Mismatch" 错误。所有非零值都可以正常工作。我写了一个简单的模块来展示这种行为。

Sub test_format()
    Dim test_single As Single, output As String
    test_single = 0#
    output = Str(Format(test_single, "###.#"))
    Debug.Print test_single; output
End Sub

您需要删除 Str() 函数

Sub test_format()
    Dim test_single As Single, output As String
    test_single = 112.25
    output = Format(test_single, "##0.0")
    Debug.Print output
End Sub

我的输出:

112.3

编辑:将格式更新为“##0.0”。现在,如果您获得值 0.0,它不仅会 return " . ",而且实际上会 return 0.0