VBA code to detect which key the user has pressed in a text box

FaheemAhmadGul
FaheemAhmadGul used Ask the Experts™
on
I would like code against the KeyPress event of a TextBox in VBA application. I would like to detect which key has been pressed by the user when the user presses a key. I am wondering if there is way of doing that.
I would like in particular to know if the user has pressed the space key or a number key.
Thank you for your help.

Private Sub TextBoxI_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

'need to know which key the user has pressed and take a an action based on the key pressed for example display a message box when the user presses space key.

End Sub

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2008
Commented:
The following is a start

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

'need to know which key the user has pressed and take a an action based on the key pressed for example display a message box when the user presses space key.

Select Case KeyAscii

    Case 32 'space
        'do something when the space is typed

    Case 48 To 57 'numeric value 0 to 9
        'do something when a numeric key value is typed (between 0 to 9)

End Select

End Sub

Open in new window

Author

Commented:
Many thanks.
Greatly appreciated!
Top Expert 2008

Commented:
Glad it worked out for you!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial