gpt4 book ai didi

VB6 IsNumeric 会出错吗?

转载 作者:行者123 更新时间:2023-12-04 16:21:12 28 4
gpt4 key购买 nike

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

我问是因为我遇到了类型不匹配错误,所以我在尝试强制转换之前使用 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

最佳答案

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

根据 IsNumeric 上的 MSDN 文档:

  • IsNumeric 返回 True 如果数据
    表达式类型为 bool 型、字节型、
    十进制、 double 、整数、长整数、
    SByte、Short、Single、UInteger、
    ULong,或 UShort,或一个对象
    包含这些数字类型之一。
    如果 Expression 是,它也返回 True
    一个 Char 或 String 可以是
    成功转换为数字。
  • IsNumeric 返回 False 如果表达式
    是数据类型日期或数据类型
    对象并且它不包含
    数字类型。 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))

    编辑:在您澄清之后,您似乎正在获得溢出转换。首先尝试使用 Long 和 CLng() 而不是 CInt()。尽管如此,该条目仍有可能是 Int64,这在使用 VB6 时更加困难。

    我已将以下代码用于 LARGE_INTEGER 和 Integer8 类型(均为 Int64),但它可能不适用于您的情况:
    testValue = CCur((inputValue.HighPart * 2 ^ 32) + _
    inputValue.LowPart) / CCur(-864000000000)

    这个例子来自 LDAP password expiration example ,但就像我说的,它可能适用于您的场景,也可能不起作用。如果你没有 LARGE_INTEGER 类型,它看起来像:
    Private Type LARGE_INTEGER
    LowPart As Long
    HighPart As Long
    End Type

    搜索 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

    关于VB6 IsNumeric 会出错吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/470041/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com