IsInteger (VB Function)

Visual Basic Modules Add comments

Here are two different ways I've come up with for determining if a number is an integer in Visual Basic. The first way, IsInteger, is a function that will return true if you pass it a VB Integer data type. The second way, IsIntegerStr, is a function that will return true if you pass it a VB Integer data type or an integer in string form.

Download IsInteger.bas (May 31, 2006)

MSDN Links
 Int Function Reference
 IsNumeric Function Reference

'This function will return true if you pass it a VB Integer data type.
Public Function isInteger(v As Variant) As Boolean
 isInteger = IIf(VarType(v) = vbInteger, True, False)
End Function

'This function will return true if you pass it a VB Integer data type or an integer in string form.
Public Function isIntegerStr(v As Variant) As Boolean
 On Error Goto isIntegerStrError
 If VarType(v) = vbInteger Or v = vbInteger Or LCase$(CStr(v)) = "vbinteger" Then
  isIntegerStr = True
  Exit Function
 End If
 If CStr(v) = "" Then
  isIntegerStr = False
  Exit Function
 End If
 'only continue if we have postive whole numbers (or negative whole numbers)
 If isAllNumbers(v) = True Or isValidNegative(v) = True Then
  If Val(v) >= -32768 And Val(v) <= 32767 Then
   isIntegerStr = True
  Else 'number is out of range
   isIntegerStr = False
  End If
 Else 'input is Not a valid positive or negative number
  isIntegerStr = False
 End If
 Exit Function
 isIntegerStrError:
 MsgBox "An Error has occured..." & vbLf & vbLf & "Error Number: " & Err.Number & vbLf & "Error Description: " & Err.Description & vbLf, vbCritical + vbOKOnly
 isIntegerStr = False
End Function

'isAllNumbers() returns true if you pass it anything that contains numbers only (i.e. a positive whole number)
Public Function isAllNumbers(v As Variant) As Boolean
 On Error Goto isAllNumbersError
 If CStr(v) = "" Or VarType(v) = vbNull Then 'if nothing was passed
  isAllNumbers = False
  Exit Function
 End If
 Dim i As Integer
 For i = 1 To Len(CStr(v))
  If Mid(CStr(v), i, 1) > "9" Or Mid(CStr(v), i, 1) < "0" Then
   isAllNumbers = False
   Exit Function
  End If
 Next i
 isAllNumbers = True
 Exit Function
 isAllNumbersError:
 MsgBox "An Error has occured..." & vbLf & vbLf & "Error Number: " & Err.Number & vbLf & "Error Description: " & Err.Description & vbLf, vbCritical + vbOKOnly
 isAllNumbers = False 'default To false In Case of Error
End Function

'isValidNegative() returns true if the passed number is a valid negative whole number
Public Function isValidNegative(v As Variant) As Boolean
 If Len(CStr(v)) >= 2 Then
  If Left(CStr(v), 1) = "-" And isAllNumbers(Mid(CStr(v), 2)) = True Then
   isValidNegative = True
  Else
   isValidNegative = False
  End If
 Else 'a valid negative number must be at least 2 characters Long (i.e. "-1")
  isValidNegative = False
 End If
End Function

Leave a Comment

Entries RSS Comments RSS Log in