Checking if variable is a number (1 Viewer)

anb001

Registered User.
Local time
Today, 05:20
Joined
Jul 5, 2004
Messages
197
I would like to check if contents of a text box is a whole number, i.e. not a decimal number and no letters. If it is not a whole number, it should set focus to the specific text box, and select contents, i.e. focus has to stay in text box, as long as contents is not a whole number.

So far I have:

Code:
If Not IsNumeric(me.txtPrint) Then
Msgbox("Some text here.")
Else
End If

Can someone assist?
 

VilaRestal

';drop database master;--
Local time
Today, 04:20
Joined
Jun 8, 2011
Messages
1,046
Code:
If Not IsNumeric(me.txtPrint) Then
    Msgbox("Some text here.")
Else
    If Me.txtPrint <> Int(Me.txtPrint) Then
        Msgbox("Some text here.")
    Else
    End If
End If

To actually do everything you want it to I would do this:

Code:
Private Sub txtPrint_BeforeUpdate(Cancel As Integer)
    Cancel = Not IsNumeric(Me.txtPrint)
    If Not Cancel Then Cancel = (Me.txtPrint <> CStr(Int(Me.txtPrint)))
    If Cancel Then
        MsgBox "Only a whole number is allowed"
        txtPrint.SelStart = 0
        txtPrint.SelLength = Len(txtPrint.Text)
    End If
End Sub

Edit: Testing it, for some reason it needed the CStr.
 
Last edited:

anb001

Registered User.
Local time
Today, 05:20
Joined
Jul 5, 2004
Messages
197
Excellent. Thanks..
 

jdraw

Super Moderator
Staff member
Local time
Yesterday, 23:20
Joined
Jan 23, 2006
Messages
15,423
Here's another and a test routine.
Code:
Function IsWholenumber(InValue As String) As Boolean
Dim j As Integer
On Error Resume Next
IsWholenumber = True
 For j = 1 To Len(InValue)
    If Mid(InValue, j, 1) Like "#" Then
    Else
    IsWholenumber = False
      Exit For
    End If
 Next j
End Function
Code:
Sub testWholenumber()
Dim i As Integer
Dim x(5) As String
x(0) = "1234az67"
x(1) = "aabc kk"
x(2) = "123,456,000"
x(3) = "123.49"
x(4) = "13643"
x(5) = "12345678"
' Included the "," in testing, but chose to remove it with Replace
For i = 0 To 5
    x(i) = Replace(x(i), ",", "")
    MsgBox x(i) & " is whole number is " & IsWholenumber(x(i))
Next i
End Sub
 

Users who are viewing this thread

Top Bottom