KeyPress Event

C

Conrado Capistrano

Hello NG,

Please tell me why the sendkeys statement does not work here in my code.
Also, why is it that when I press backspace it does not trigger the
keypress event even though the help file said that it will trigger the
event.

TIA

Jon-jon


Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case 48 To 57 'Nos 0 - 9
Exit Sub
Case Else
Application.EnableEvents = False
SendKeys "{BACKSPACE}", True
Application.EnableEvents = True
MsgBox "Please enter numeric character only."
End Select
End Sub
 
C

Chip Pearson

Conrado,

Try the following instead:

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case 48 To 57 'Nos 0 - 9
Exit Sub
Case Else
Application.EnableEvents = False
KeyAscii = 0
Application.EnableEvents = True
MsgBox "Please enter numeric character only."
End Select
End Sub
 
T

Tom Ogilvy

Just to add.
I have never seen a need to enable or disable events when you change the key
ascii value. I believe those two lines can be deleted.

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case 48 To 57 'Nos 0 - 9
Exit Sub
Case Else
KeyAscii = 0
MsgBox "Please enter numeric character only."
End Select
End Sub

worked fine for me without interfering with the users ability to edit the
information in the box. I saw no evidence that this event was fired by a
backspace key.
 
R

Ron de Bruin

Try to avoid Sendkey Conrado
It is not reliable

Maybe you like this one
It will only allow digits 0 thru 9


Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Dim i As Integer
If KeyAscii < 48 Or KeyAscii > 57 Then
' only allow digits 0 thru 9
KeyAscii = 0
End If
End Sub
 
C

Conrado Capistrano

Thanks Ron!


Ron de Bruin said:
Try to avoid Sendkey Conrado
It is not reliable

Maybe you like this one
It will only allow digits 0 thru 9


Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Dim i As Integer
If KeyAscii < 48 Or KeyAscii > 57 Then
' only allow digits 0 thru 9
KeyAscii = 0
End If
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top