excelvbaintegerlong-integer

Test if value is Long or Integer (no decimal places)


I need to test if the value in textbox1 and textbox2 is integer or long (with no decimal places).

I tried something like this:

    Dim x As Integer
    Dim y As Integer

    x = TextBox1.Value
    y = TextBox2.Value

    If x = Int(x) Then
        'my code
    Else
        MsgBox("value is not an integer")

If I put x=2.3 it does not display MsgBox but it rounds the value to 2.


Solution

  • Since you've specified the type of x to be an Integer, the conversion from the text box string to the Integer has already taken place. Hence Int(x) is a no-op.

    One fix would be to use something like

    If IsNumber(TextBox1.Value) Then
        If Fix(TextBox1.Value) = TextBox1.Value Then
            'I am an integeral type.
        End If
    End If
    

    Here, Fix truncates a numeric type, and I'm relying on VBA to make the correct comparison. Note that VBA doesn't implement a short-circutted And so you need to use a nested If or similar.