Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a specific key was pressed?

I'm wondering is there a way to detect if a specific key (like backspace) was pressed. This is what I'm shooting for:

Private Sub SomeTextBox_Change()

    If len(Me.SomeTextBox.Value) = 3 and KEYPRESSED is NOT BACKSPACE Then
         <.......Code Here>
    Else
         <.......Code Here>
    End if

End Sub
like image 484
Ollie Avatar asked Nov 30 '22 10:11

Ollie


2 Answers

You should use KeyPress event instead of Change event:

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

    If Len(Me.SomeTextBox.Value) = 3 And KeyAscii <> 8 Then 'Backspace has keycode = 8.
         <.......Code Here>
    Else
         <.......Code Here>
    End If

End Sub

Full list of keycodes you can find here: http://www.asciitable.com/

like image 154
mielk Avatar answered Dec 05 '22 01:12

mielk


This example assigns "InsertProc" to the key sequence CTRL+PLUS SIGN and assigns "SpecialPrintProc" to the key sequence SHIFT+CTRL+RIGHT ARROW.

Application.OnKey "^{+}", "InsertProc" 
Application.OnKey "+^{RIGHT}","SpecialPrintProc"

for more examples and infos go on : https://msdn.microsoft.com/en-us/library/office/aa195807%28v=office.11%29.aspx

like image 44
xs6 Avatar answered Dec 04 '22 23:12

xs6