How to intercept the user pressing a particular keyboard key when a UserForm control has the focus

Article contributed by Ibby and Dave Rado

If a you want to know if the user presses the Tab key or the Backspace key in a text box, for example; or the Down Arrow key in a Listbox or on an Option button, you can use code such as the following:

Private Sub OptionButton1_KeyDown(ByVal KeyCode As _
        MSForms.ReturnInteger, ByVal Shift As Integer)

If
KeyCode = wdKeyTab Then
    'Your code here
End If

End Sub

There are wdKey constants for most, but not all, of the KeyCodes you are likely to want to use; to get the full list of the constants, press F2 to open the Object Browser and search for wdKey.

So for example, there is a constant for the backspace key:

Private Sub TextBox1_KeyDown(ByVal KeyCode As _
        MSForms.ReturnInteger, ByVal Shift As Integer)

If
KeyCode = wdKeyBackspace Then
    'Your code here
End If

End Sub

But for some strange reason, there is no constant for the Down Arrow key. To get the value to use for KeyCodes that have no constant, use code such as the following:

Private Sub ListBox1_KeyDown(ByVal KeyCode As _
        MSForms.ReturnInteger, ByVal Shift As Integer)

MsgBox KeyCode

End Sub

If you do that, click the Listbox and press the Down Arrow key, it returns 40; so you can then use:

Private Sub ListBox1_KeyDown(ByVal KeyCode As _
        MSForms.ReturnInteger, ByVal Shift As Integer)

If
KeyCode = 40 Then    'Down Arrow key was pressed
    'Your code here
End If

End Sub


Click to view Terms of Use page

Click to view Disclaimer page