【问题标题】:Convert TextBox.Value to Double into VBA (Excel 2013)将 TextBox.Value 转换为 Double 到 VBA (Excel 2013)
【发布时间】:2017-02-23 13:14:00
【问题描述】:

我的表单中有 TextBox,用户可以在其中输入一个值。 在 VBA 中,我需要将值从字符串转换为双精度值。

我这样做是这样的:

Private Sub UserForm_Initialize()

    '....some code
    Dim new_value As Double
    new_value = CDbl(TextBox6.Value)

End sub

但我收到以下错误:

【问题讨论】:

    标签: vba excel type-conversion double


    【解决方案1】:

    CDbl 需要一个数字,但如果文本框为空,则 TextBox6.Value 是一个空字符串。 CDbl 无法将空字符串转换为双精度。

    您可以先验证文本框是否为数值以避免这种情况

    If IsNumeric(TextBox6.Value) Then
        new_value = CDbl(TextBox6.Value)
    Else
        new_value = 0
    End If
    

    或者Val() 函数可能是您的一个选择。

    new_value = Val(TextBox6.Value)
    

    【讨论】:

    • 谢谢!我做到了:new_value = CDbl(Replace(TextBox6.Value, ".", ",")) 并且也有效。
    【解决方案2】:

    如果允许用户使用其他字符(例如,$ 符号),则以下函数可能有用:

    '
    ' Skips all characters in the input string except
    '  the first negative-sign, digits, and the first dot
    '
    Function ParseNumber(ByVal s As String) As Double
        ParseNumber = 0#
        Dim char As String
        Dim i As Integer
        Dim digits$
        Dim isNegative As Boolean
        Dim isPastDot As Boolean
        For i = 1 To Len(s)
            char = Mid(s, i, 1)
            If char >= "0" And char <= "9" Then
                digits = digits + char
            ElseIf char = "-" Then
                If Len(digits) <= 0 Then
                    isNegative = True
                End If
            ElseIf char = "." Then
                If Not isPastDot Then
                    isPastDot = True
                    digits = digits & "."
                End If
            End If
        Next i
        ParseNumber = CDbl(digits)
        If isNegative Then
            ParseNumber = 0 - ParseNumber
        End If
    End Function
    

    【讨论】:

    • 如果对其他方式感兴趣(将数字转换为字符串),请查看FormatNumber(...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 2023-04-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多