我有一个像number= InputBox("Number for:", "Number:")
声明,号码被声明为Dim number As Double
但是当我进入一个双数,例如5.4,进入的InputBox并将其传送到细胞中,所述细胞显示我删除了这个点。的InputBox不接受双号VBA的excel
我该如何解决这个问题?
THX
我有一个像number= InputBox("Number for:", "Number:")
声明,号码被声明为Dim number As Double
但是当我进入一个双数,例如5.4,进入的InputBox并将其传送到细胞中,所述细胞显示我删除了这个点。的InputBox不接受双号VBA的excel
我该如何解决这个问题?
THX
如果要检测哪些设置你的Excel使用的小数点分隔符,试试下面的代码:
MsgBox "Excel uses " & Chr(34) & Application.DecimalSeparator & Chr(34) & " as a decimal seperator"
,如果你想将其更改为.
,然后用下面的一行:
Application.DecimalSeparator = "."
有趣的方法。 “Application.DecimalSeparator”设置是否会在会话中持续存在(即下次打开Excel时)。如果您同时打开其他工作簿,那又如何呢? – Noceo
@Noceo如果你不想修改其他文件的设置 –
@ShaiRado,你可以在关闭Sub或者Workbook_Close事件时修改它吗?我必须将它插入到我的代码中Application.DecimalSeparator =“。”'。我真的不明白,就是我很困惑。 – flowers1234
不幸的是,VBA是在小数seprators处理分歧可怕。在你的情况下,你应该使用逗号(,
),而不是标点/点(.
)。
编辑:使用Application.DecimalSeparator
方法,它现在可以工作,无论区域设置如何。但请注意,如果您更改Excel的逗号分隔符设置(似乎VBA会忽略此设置),似乎会导致一些问题。如果你不但是改变的是,例如应在所有其他CA工作
Sub GetNumberFromInputBox()
Dim val As String
Dim num As Double
'Get input
val = InputBox("Number for:", "Number:")
Debug.Print Application.DecimalSeparator
If IsNumeric(val) Then
'Try to convert to double as usual
num = CDbl(val)
'If the dot is removed automatically, then
'you will se a difference in the length. In
'those cases, replace the dot with a comma,
'before converting to double
If Len(val) <> Len(num) Then
If Application.DecimalSeparator = "," Then
num = CDbl(Replace(val, ".", ","))
Else
num = CDbl(Replace(val, ",", "."))
End If
End If
'Pring the number
Debug.Print "You selected number: " & num
Else
'If its not a number at all, throw an error
Debug.Print "You typed " & val & ", which is not a number"
End If
End Sub
我需要这行吗?'如果Len(val)<> Len(num)Then' – flowers1234
如果VBA搞乱了你的输入,如果你输入'5.4',并且VBA转换它到'54',然后你w生病的长度有所不同(分别是3和2个字符)。这种差异是'replace()'函数的触发器,它在继续之前将点转换为逗号。 – Noceo
当我执行包含代码的代码并在此行设置断点时,如果Len(val)<> Len(num)Then num = CDbl(Replace(val,“。”,“,”)) End If '数字我得到的值54.我在输入框中输入5.4,它仍然返回54 – flowers1234
尝试'number = CDbl(InputBox(“Number for:”,“Number:”))',可能是您的系统将'.'视为千位分隔符? – PatricK
我试过了,它不起作用:(@PatricK – flowers1234
InputBox返回一个字符串,请尝试在单独的Sub来测试是否小数点被删除了。Sub IB_Test():Debug.Print“”“”&InputBox(“ Num:“,”Number:“)&”“”“:End Sub'运行并观察立即窗口。 – PatricK