Search code examples
excelvbauserformkeydown

How to assign keydown events to a userform?


I want specific keys (Enter, Right Arrow, Esc) to execute different procedures.

I have the following code but nothing is working. I tried setting KeyPreview = True, but that did not seem to change anything.

Sub UserForm1_KeyDown(ByVal KeyAscii As MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyAscii
        Case 13 'enter key
            addBtn_Click
        Case 39 'right arrow
            skipBtn_Click
        Case 27 'escape key
            exitBtn_Click
        Case Else
    End Select
End Sub

UPDATE
Chris mentioned (below) that it should be named after the class, readjusting names helped fix some other small bugs in my form. However I've run into an issue with having the userform open on a command button click, running or clicking this gives me a 1004 error.

Private Sub blocksSorter_Click()
     Load UserForm1
     UserForm1.Show
End Sub

Solution

  • It does not matter how you name your Userform, the event always has the name Userform_event as said in one of the comments. And you have to put the code into the class module of the userform. In this case

    Sub UserForm_KeyDown(ByVal KeyAscii As MSForms.ReturnInteger, ByVal Shift As Integer)
        Select Case KeyAscii
            Case 13 'enter key
                addBtn_Click
            Case 39 'right arrow
                skipBtn_Click
            Case 27 'escape key
                exitBtn_Click
            Case Else
        End Select
    End Sub
    

    This article gives a quite good overview and introduction to userforms