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!

The KeyPress Event and Backspace

Status
Not open for further replies.

eelsar

Technical User
May 20, 2002
36
US
The following code doesn't allow letters to be entered.

Private Sub txtChildNumberInFamily_KeyPress(KeyAscii As Integer)
If KeyAscii < Asc(&quot;0&quot;) Or KeyAscii > Asc(&quot;9&quot;) Then KeyAscii = 0
End Sub

However the backspace character also has an ASCII code that will be ignored by this code. That means if I type in a wrong number I can't backspace it

how do I correct this?

Thank you!
 

Private Sub txtChildNumberInFamily_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case Is = 8
' OK backspace
Case Is < 48, Is > 57
KeyAscii = 0
'MsgBox &quot; this value must be numeric&quot;
Beep
End Select
End Sub

Hope this helps.

 
I tried what you wrote but it doesn't work.
If I enter a number and try to backspace, backspace doesn't move, I only can get rid of the wrong number by selecting it and then pressing delete.
Do you have any other suggestions?
Thank you!
 

Whom's code did you try. If You put Mine Prior to your numeric check it should work and should BobWman's

For The best english like readable code I would try something like this

Private Sub Text1_KeyPress(Keyascii As Integer)

On Error GoTo EH

Dim C As String

If KeyAscii = vbKeyBack Then Exit Sub

C = Chr(KeyAscii)

Select Case C
Case &quot;0&quot; To &quot;9&quot;
Case Else
KeyAscii = 0
End Select

Exit Sub
EH:

MsgBox Err.Description

End Sub

This is definitly not the only way to do this code but it is fairly self documenting (I Know, A whole different thread!)

Good Luck
 

I agree that any of these code samples should work. Did you put them in the correct event?
 
Is there a way to detect the Delete key in the KeyPress event? It doesn't seem to throw an Ascii code.
 

No, I belive you would have to use the KeyDown or KeyUp events.
 
You have to use the Keyup or KeyDown event, rather than Keypress.

The ascii code(Keycode) is 46.

It may not be necessary to add any code for this, though.
 
You have to use the Keyup or KeyDown event, rather than Keypress.

The ascii code(Keycode) is 46.

It may not be necessary to add any code for this, though.
 
Interesting. Why is it called KeyCode in those other events and KeyAscii in KeyPress? Why doesn't it work in KeyPress?
 

KeyAscii = Printable keys
KeyCode = all keys

Just a guess but sounds good :)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top