VB6 Can IsNumeric会出错吗?

5 vb6 casting isnumeric

是否可以使用IsNumeric()测试字符串并返回true,但是当您使用CInt()将相同的字符串转换为整数并将其分配给integer类型的变量时,它会给出类型不匹配错误?

我问因为我得到了一个类型不匹配错误,所以我在尝试强制转换之前使用IsNumeric()检查字符串是否为数字,但我仍然得到错误.

我正用这个撕掉我的头发.

这是有问题的代码. iGlobalMaxAlternatives = CInt(strMaxAlternatives)是发生错误的地方.

Dim strMaxAlternatives As String
Dim iGlobalMaxAlternatives As Integer
iGlobalMaxAlternatives = 0
bSurchargeIncInFare = True

strMaxAlternatives = ReadStringKeyFromRegistry("Software\TL\Connection Strings\" & sConn & "\HH", "MaxAlt")

If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
    iGlobalMaxAlternatives = CInt(strMaxAlternatives)
End If
Run Code Online (Sandbox Code Playgroud)

Rya*_*yan 6

由于最大整数大小,您可能会出现溢出; 货币类型实际上对大数字表现非常好(但要注意任何地区问题).有关Int64的讨论,请参阅下面的编辑.

根据有关IsNumeric的 MSDN文档:

  • 如果Expression的数据类型为Boolean,Byte,Decimal,Double,Integer,Long,SByte,Short,Single,UInteger,ULong或UShort,或者包含其中一种数字类型的Object,则IsNumeric返回True.如果Expression是可以成功转换为数字的Char或String,它也会返回True.

  • 如果Expression的数据类型为Date或数据类型为Object,并且它不包含数字类型,则IsNumeric返回False.如果Expression是无法转换为数字的Char或String,则IsNumeric返回False.

由于您遇到类型不匹配,因此Double可能会干扰转换.IsNumeric不保证它是一个整数,只是它匹配其中一个数字可能性.如果数字是双精度,则可能是区域设置(逗号与句点等等)导致异常.

您可以尝试将其转换为double,然后转换为整数.

' Using a couple of steps
Dim iValue As Integer
Dim dValue As Double
dValue = CDbl(SourceValue)
iValue = CInt(iValue)
' Or in one step (might make debugging harder)
iValue = CInt(CDbl(SourceValue))
Run Code Online (Sandbox Code Playgroud)

编辑:澄清后,您似乎正在进行溢出转换.首先尝试使用Long和CLng()代替CInt().但是仍然有可能输入Int64,使用VB6更难.

我已将以下代码用于LARGE_INTEGER和Integer8类型(均为Int64),但它可能不适用于您的情况:

testValue = CCur((inputValue.HighPart * 2 ^ 32) + _
                  inputValue.LowPart) / CCur(-864000000000)
Run Code Online (Sandbox Code Playgroud)

此示例来自LDAP密码到期示例,但我说它可能在您的方案中有效或可能无效.如果您没有LARGE_INTEGER类型,它看起来像:

Private Type LARGE_INTEGER
    LowPart As Long
    HighPart As Long
End Type
Run Code Online (Sandbox Code Playgroud)

搜索LARGE_INTEGER和VB6以获取更多信息.

编辑:对于调试,暂时避免错误处理,然后在通过麻烦的线后重新打开它可能是有用的:

If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
    On Error Resume Next
    iGlobalMaxAlternatives = CInt(strMaxAlternatives)
    If Err.Number <> 0 Then
        Debug.Print "Conversion Error: " & strMaxAlternatives & _
                    " - " & Err.Description
    EndIf
    On Error Goto YourPreviousErrorHandler
End If
Run Code Online (Sandbox Code Playgroud)