Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleSee if a string is an integer
Keywordsstring, integer
CategoriesStrings
 
The IsNumeric function returns some odd values. For example, IsNumeric("10-") is true even though you probably don't want to consider "10-" to be a valid integer.

This function tests to see whether a value is an integer.

Thanks to Hisham Nassef

 
Private Function IsInteger(str As String) As Boolean
Dim i As Byte
Dim CharAscii As Integer
Dim Count As Byte

    For i = 1 To Len(str)
        CharAscii = Asc(Mid(str, i, 1))
        If (CharAscii > 47 And CharAscii < 58) Then
            Count = Count + 1
        Else
            If i = 1 Then
                If CharAscii <> 43 And CharAscii <> 45 Then
                    IsInteger = False
                    Exit For
                End If
            Else
                IsInteger = False
                Exit For
            End If
            Count = Count + 1
        End If
    Next

    If Count = Len(str) Then
        If Val(str) > 32767 Or Val(str) < -32768 Then
            IsInteger = False
        Else
            IsInteger = True
        End If
    End If
End Function

Private Sub Command1_Click()
    lblIsNumeric.Caption = Format(IsNumeric(Text1.Text))
    lblIsInteger.Caption = Format(IsInteger(Text1.Text))
End Sub
 
Formatted by Neil Crosby
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated