hey need some help guys. for example i have a text box and i will have input in it. but only numeric ones are allowed to be inputted in the text box if a character for example "a" is pressed the text box will not change and type the "a" and if a numeric button for example is 1, the text box will have 1. how can i do this? thanks.

hi dc_241

try this
if keyascii>65 or keyascii<97
msgbox"error"
endif

try this following code :

' This code for string input or other (comma,drop,question mark etc) except numeric

Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii < 48 Or KeyAscii > 57 Then
Text1.Locked = False
Else
Text1.Locked = True
End If
End Sub

' This code for numeric input only, other input cannot be written

Private Sub Text2_KeyPress(KeyAscii As Integer)
If KeyAscii < 48 Or KeyAscii > 57 Then
Text2.Locked = True
Else
Text2.Locked = False
End If
End Sub

' This code for string input only (drop, comma, question mark cannot be written)

Private Sub Text3_KeyPress(KeyAscii As Integer)
If KeyAscii > 65 Or KeyAscii > 97 Then
Text1.Locked = False
Else
Text1.Locked = True
End If
End Sub

actually you can combine this with ascii code. look the code in ascii table and you can let what input can be written.

OK.hope this helps..

You don't have to lock the text box, just set KeyAscii to 0. Also, you need to handle the backspace key to allow users to fix errors:

Private Sub Text1_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case 48 To 57, 8
'Let these key codes pass through
Case Else
'All others get trapped
KeyAscii = 0
End Select
End Sub

commented: Nice Recovery +1

thx SCBWV...
nice recovery for my post...

Try this code if it help...

If (keyascii<48 or keyascii>57) and keyascii<>vbkeyback then
keyascii=0
end if

You can also try the isnumeric() function at the keypress event...
For example...

Private Sub Text1_KeyPress(KeyAscii As Integer)
If Not IsNumeric(Chr(KeyAscii)) And Not KeyAscii = 8 Then KeyAscii = 0
End Sub

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.