21

I am working on a project which allows kids to send a message to Santa. Unfortunately, if they enter a string instead of an integer in the AGE field, the program crashes and returns Conversion from string "[exampleString]" to type 'Double' is not valid. Is there any way to check if they have entered an integer or not? This is the code.

If childAge > 0 And childAge < 150 Then
    fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
    fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If

Thanks, Kai :)

9 Answers 9

48

A very simple trick is to try parse the string as an Integer. If it succeeds, it is an integer (surprise surprise).

Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
    ' childAge successfully parsed as Integer
Else
    ' childAge is not an Integer
End If
Sign up to request clarification or add additional context in comments.

Comments

9

Complementing Styxxy's response, if you dont need a result just replace it by vbNull:

If Integer.TryParse(childAge, vbNull) Then

Comments

3

IsNumeric is built into VB, and will return a true/false

If IsNumeric(childAge) AndAlso (childAge > 0 And childAge < 150) Then
    fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
    fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If

2 Comments

Thanks, that's quite helpful!
If the child puts in a number and letters this will still bug out
3

You could perform the following two tests to be reasonably certain that the input you're getting is an integer:

If IsNumeric(childAge) AndAlso (InStr(1, childAge, ".") <> 0) Then
    fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
    If childAge < 0 OrElse childAge > 150 Then
        fmSecA2 = "I don't believe it's possible to be" & childAge & " years old..."
    End If
Else
    fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"

The InStr function returns zero if it doesn't find the string that is being looked for, and so when combining that test with IsNumeric, you also rule out the possibility that some floating point data type was entered.

1 Comment

this assumes '.' as a decimal separator - which may be ok in most cases. but may be better to use Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparato instead
1

You can use this.

Sub checkInt() 
    If IsNumeric(Range("A1")) And Not IsEmpty(Range("A1")) Then 

        If Round(Range("A1"), 0) / 1 = Range("A1") Then 
            MsgBox "Integer: " & Range("A1") 
        Else 
            MsgBox "Not Integer: " & Range("A1") 
        End If 
    Else 
        MsgBox "Not numeric or empty" 
    End If 
End Sub 

1 Comment

A bit confusing, but ok. Thanks for helping! :)
0

Working from Styxxy's answer, if you parse as a byte rather than an integer, then it also checks negative ages and maximum age of 255 all in one go.

Dim childAgeAsByte As Byte
If Byte.TryParse(childAge, childAgeAsByte) Then
    ' childAge successfully parsed as Byte
Else
    ' childAge is not a Byte
End If

Kristian

Comments

0
Dim Input 

 Input = TextBox1.Text
 If Input > 0 Then 
   ............................
   ............................
 Else 
   TextBox2.Text = "Please only enter positive integers"
 End If

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
0
Try
    If TextBox1.Text > 0 Then
        Label1.Text = "Integer"
    End If
Catch ex As Exception
    Label1.Text = "String"
End Try

With this you can put anything in TextBox1, if you put text then you get Label1 is string and if you put number then you get it's integer

Comments

-1

In .Net you may use GetType() to determine the data type of a variable.

Dim n1 As Integer = 12
Dim n2 As Integer = 82
Dim n3 As Long = 12

Console.WriteLine("n1 and n2 are the same type: {0}",
                  Object.ReferenceEquals(n1.GetType(), n2.GetType()))
Console.WriteLine("n1 and n3 are the same type: {0}",
                  Object.ReferenceEquals(n1.GetType(), n3.GetType()))
' The example displays the following output: 
'       n1 and n2 are the same type: True 
'       n1 and n3 are the same type: False  

Based on the above sample you can write a code snippet:

If childAge.GetType() = "Integer" then '-- also use childAge.GetType().Name = "Int32"
  ' do something
End if

5 Comments

How does that answer the question?
@Meta-Knight I am merely showing a sample code with GetType() to find out the variable Type. OP may use it to define whether it's an integer, long, boolean etc type. Sigh you downvote me :(
This question was in regards to determining if a String can successfully parse to an Integer. Using GetType wouldn't help here. It would be of type String.
@JasonTyler the title says "VB - Check if a variable is an integer"
@Meta-Knight there are two other answers checking on integer here! So it's not very fair to downvote my answer when I am providing a proper way of checking the Type. Passing the String as an Integer is primary, however checking the Type is also within the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.