Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check Data and exit sub if not an integer

Status
Not open for further replies.

bdmangum

Technical User
Dec 6, 2006
171
US
Hi,

I need to take a user input into a form.textbox and verify it is an integer before the program continues. it's critical the user inserts only an integer. I'm at a loss as to how to accomplish this though. I'll insert the code I've tried below.

Code:
Private Sub TextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)

If TextBox.Text <> "" Then
    If TextBox.Text > 0 And TextBox.Text < 100000000 Then
        Exit Sub
    Else
        Response = MsgBox("Please insert a valid number.", vbOKOnly, "Error")
    End If
End If

End Sub

The problem with this code is that if they enter anything besides an integer it returns a data type mismatch error, so it doesn't accomplish it's purpose. Ideas?
 
Code:
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)

Dim Number As Long
Dim Response

On Error GoTo ErrorHandler

Number = TextBox2.Text
Exit Sub
ErrorHandler:
TextBox2.Text = ""
Response = MsgBox("Please insert a valid number.", vbOKOnly, "Error")
End Sub
 
Also, since you don't need to return a value from the message box:
Code:
MsgBox "Please insert a valid number.", vbOKOnly, "Error"
 
Thanks for the help! I just inserted it and it works great! I never would have thought of that since I haven't ever used the errorhandler. It seems like a nice tool. Thanks again!
 
Gerry makes a good point. Another thing you could do is check each charactor on the change event. If it is invalid just delete it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top