VB6 Can IsNumeric be wrong?

2019-04-29 16:24发布

Is it possible to test a string with IsNumeric() and for it to return true, but when you cast that same string to an integer using CInt() and assign it to a variable of type integer that it will give a type mismatch error?

I ask because I was getting a type mismatch error, so I used IsNumeric() to check the string was numeric before trying to cast it, but I still get the error.

I am tearing my hair out with this.

Here is the code in question. iGlobalMaxAlternatives = CInt(strMaxAlternatives) is where the error is occuring.

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

10条回答
Melony?
2楼-- · 2019-04-29 17:20

Your best bet is to start logging the errors with the actual values it's working with so you can figure out whats going on.

查看更多
倾城 Initia
3楼-- · 2019-04-29 17:21

VB6 doesn't provide good methods to guarantee CInt won't fail. I've found the simplest way is to just use error-handling.

function TryParse(byval text as string, byref value as integer) as boolean
  on error resume next
  value = CInt(text)
  TryParse = (err.number = 0)
endfunction

Of course your error-handling preferences may vary.

查看更多
Deceive 欺骗
4楼-- · 2019-04-29 17:21

IsNumeric will return true if it can convert the string to a number. Even if there are non-numeric characters in the string. I always loop though the string one character at a time and test each character. If one character fails then I can return an error.

查看更多
我想做一个坏孩纸
5楼-- · 2019-04-29 17:27

Two options...

Change

If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
    iGlobalMaxAlternatives = CInt(strMaxAlternatives)
End If

To

If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
    iGlobalMaxAlternatives = CDbl(strMaxAlternatives) ' Cast to double instead'
End If

Or

If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
    If CDbl(strMaxAlternatives) Mod 1 = 0 Then ' Make sure there\'s no decimal points'
        iGlobalMaxAlternatives = CInt(strMaxAlternatives)
    End If
End If
查看更多
登录 后发表回答