将 TextBox.Value 转换为 Double 到 VBA (Excel 2013)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42416794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert TextBox.Value to Double into VBA (Excel 2013)
提问by 4est
I have TextBox into my form, where user can input a value. In VBA I need to convert the value from string to double.
我的表单中有 TextBox,用户可以在其中输入一个值。在 VBA 中,我需要将值从字符串转换为双精度值。
I'm doing it like:
我这样做:
Private Sub UserForm_Initialize()
'....some code
Dim new_value As Double
new_value = CDbl(TextBox6.Value)
End sub
But I'm getting the error below:
但我收到以下错误:
回答by P??
CDbl
expects already a number but if the textbox is empty then TextBox6.Value
is an empty string. CDbl
can't cast an empty string into a double.
CDbl
期望已经是一个数字,但如果文本框为空,TextBox6.Value
则为空字符串。CDbl
不能将空字符串转换为双精度。
You can validate if the textbox is a numeric value first to avoid this
您可以先验证文本框是否为数值以避免这种情况
If IsNumeric(TextBox6.Value) Then
new_value = CDbl(TextBox6.Value)
Else
new_value = 0
End If
Alternatively the Val()
function might be an option for you.
或者,该Val()
功能可能是您的一个选择。
new_value = Val(TextBox6.Value)
回答by Top-Master
In case the user is allowed to use other characters (for example, the $
sign), then the below function could be useful:
如果允许用户使用其他字符(例如,$
符号),则以下函数可能很有用:
'
' 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