How to detect if a specific key was pressed?

Ollie picture Ollie · Nov 26, 2015 · Viewed 17.1k times · Source

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

Answer

mielk picture mielk · Nov 26, 2015

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/