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

Numeric Only dataype in textbox

Status
Not open for further replies.

TJLMO

MIS
Feb 12, 2002
15
US
I am attempting to ensure that a user enters only positive integers into a textbox on a form. I am attempting to use the function IsNumeric() as part of this check. However, when I enter 555 and then move the cursor inbetween the last and middle 5 and enter a 'd' or 'e' (i.e.- 55d5 or 55e5) the IsNumeric function returns 5500000. This also occurs with 777, 666, 555, 444, 333, and 222. Any ideas on how I could better insure the user enters only a number into the textbox. Thanks in advance.
 
'* The following code allows only numbers in the text box

Private Sub text1_KeyPress(KeyAscii As Integer)

If KeyAscii = 46 Then

KeyAscii = 0

End If

If Chr(KeyAscii) Like &quot;#&quot; <> True And KeyAscii <> vbKeyBack And KeyAscii <> vbKeyDelete Then

KeyAscii = 0

End If

End Sub
 
Here's one way to do it:

Private Sub Text1_Validate(Cancel As Boolean)

For i = 1 To Len(Text1)
'*** Make sure all characters are 0 through 9.
If Asc(Mid(Text1, i, 1)) < 48 Or Asc(Mid(Text1, i, 1)) > 57 Then
'*** Invalid character in textbox.
Cancel = True
End If
Next

End Sub
 
Having seen SWI's code, this would be a simpler version of my code:

For i = 1 To Len(Text1)
'*** Make sure all characters are 0 through 9.
If Not Mid(Text1, i, 1) Like &quot;#&quot; Then
'*** Invalid character in textbox.
MsgBox &quot;?&quot;
Cancel = True
End If
Next
 
Having seen SWI's code, this would be a simpler version of my code:

For i = 1 To Len(Text1)
'*** Make sure all characters are 0 through 9.
If Not Mid(Text1, i, 1) Like &quot;#&quot; Then
'*** Invalid character in textbox.
Cancel = True
End If
Next
 
This is easier to understand than my previous post.
Credit goes to whoever wrote faq222-45.

Option Explicit

Function OnlyNumericKeys(KeyAscii As Integer) As Integer
Select Case KeyAscii
Case 8, 48 To 57 ' allow backspace, and digits
Case Else: KeyAscii = 0 ' reject everything else
End Select
OnlyNumericKeys = KeyAscii
End Function

Private Sub Text1_KeyPress(KeyAscii As Integer)
KeyAscii = OnlyNumericKeys(KeyAscii)
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top