在Windows 7上使用VB6应用程序,两行都返回TRUE,因为不考虑小数点分隔符:
IsNumeric("123.45")
IsNumeric("123,45")
在Windows 8或Windows 2012上,相同的代码返回TRUE或FALSE,具体取决于区域设置。将逗号视为区域设置中定义的小数分隔符,则:
IsNumeric("123.45") returns FALSE
IsNumeric("123,45") returns TRUE
有没有办法在不重新编译应用程序的情况下恢复“旧”行为?
答案 0 :(得分:3)
这是不您正在使用的Windows版本的新问题。它始终基于机器的区域设置。
我为我的申请所做的是我自己的职能:
Public Function IsNumber(ByRef Expression As Variant) As Boolean
Select Case VarType(Expression)
Case vbInteger, vbLong, vbSingle, vbDouble, vbCurrency, vbDate, vbBoolean, vbDecimal, vbByte
IsNumber = True
Case vbString
Dim Negative As Boolean
Dim Number As Boolean
Dim Period As Boolean
Dim Positive As Boolean
Dim X As Long
For X = 1& To Len(Expression)
Select Case Mid$(Expression, X, 1&)
Case "0" To "9"
Number = True
Case "-"
If Period Or Number Or Negative Or Positive Then Exit Function
Negative = True
Case "."
If Period Or Exponent Then Exit Function
Period = True
Case "E", "e"
If Not Number Then Exit Function
If Exponent Then Exit Function
Exponent = True
Number = False
Negative = False
Period = False
Case "+"
If Not Exponent Then Exit Function
If Number Or Negative Or Positive Then Exit Function
Positive = True
Case vbSpace, vbTab, vbVerticalTab, vbCr, vbLf, vbFormFeed
If Period Or Number Or Exponent Or Negative Then Exit Function
Case Else
Exit Function
End Select
Next X
IsNumber = Number
End Select
End Function
如果你明确地处理字符串,那么你可以简化这个功能。而且你可能也不想处理指数,所以这可能更合适:
Public Function IsNumber(ByRef Expression As String) As Boolean
Dim Negative As Boolean
Dim Number As Boolean
Dim Period As Boolean
Dim X As Long
For X = 1& To Len(Expression)
Select Case Mid$(Expression, X, 1&)
Case "0" To "9"
Number = True
Case "-"
If Period Or Number Or Negative Then Exit Function
Negative = True
Case "."
If Period Then Exit Function
Period = True
Case vbSpace, vbTab, vbVerticalTab, vbCr, vbLf, vbFormFeed
If Period Or Number Or Negative Then Exit Function
Case Else
Exit Function
End Select
Next X
IsNumber = Number
End Function
如果您需要转换号码,请使用Str()
代替CLng()
/ CInt()
/ CDbl()
/ CSng()
/ Val()
。 Str()
将句点视为小数,而不管语言环境如何,就像我上面的IsNumber()
函数一样。