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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking Text in Textbox for Numbers

Status
Not open for further replies.

JaeBrett

Programmer
Joined
May 5, 2003
Messages
196
Location
CN
I want to have something in the change event of my TextBox to verify that users are typing in numbers ... how can I do this?


Thanks guys/gals
 
Try something like this:

Private Sub Text1_Change()
Dim i as Integer
For i = 1 To Len(Text1.Text)
If IsNumeric(Mid$(Text1.Text, i, 1)) = True Then
MsgBox "No numerics allowed", vbCritical, "Invalid Character"
Text1.SetFocus
Text1.SelStart = i - 1
Text1.SelLength = 1
Exit For
End If
Next
End Sub

Swi
 
You can also use this in the keypress event.

Private Sub Text8_KeyPress(KeyAscii As Integer)
If Not (KeyAscii >= 48 And KeyAscii <= 57) And Not KeyAscii = 8 Then 'allow only number and backspace
KeyAscii = 0
Beep 'notify user of bad entry
End If
End Sub

Keyascii 8 is the backspace key. You can also add more conditions or message boxes if you like.

Thanks and Good Luck!

zemp
 
Sorry, what I posted is the inverse of what you want but you get the idea.

Swi
 

Either use the KeyPress/KeyDown events (to capture pastes) along with the Change event (to validate chars), or just the KeyPress along with the KeyDown events (to capture pastes and validate chars), or just the Change event (to validate chars) along with an Undo function (if new string is invalid, the reset to the previous value).

Otherwise anyone can still paste non-numeric characters.
 
Yes, as CCLINT mentioned you will need to deal with the user pasting values into the text box. You can add these lines to the keypress code in my previous post.

Declare a variable to be able to 'undo' the paste. I chose a modular variable.

Private m_strUndo as string

Add the following,

Private Sub Text8_Change()
If Not IsNumeric(Text8.Text) And Text8.Text <> &quot;&quot; Then
Text8.Text = m_strUndo
Text8.SelStart = Len(Text8.Text)
End If
End Sub

Private Sub Text8_GotFocus()
m_strUndo = Text8.Text
End Sub

Of course you can always look for or create an ActiceX control that will take of this automatically. Here is one example of a validation class, including the range of numbers (ie, 1 to 100 only ).




Thanks and Good Luck!

zemp
 
You could also try the MaskedEdit control

Swi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top