Search code examples
formsms-accesskeydownkeycodekeyup

MS ACCESS - How to detect arrow keys on Form.KeyDown or KeyUp events


I want to detect on a form the right and left arrow keys in VBA in order to use the Form.KeyDown or KeyUp events for X purpose.

I tried this:

Private Sub Form_KeyDown()
If KeyCode = vbKeyRightArrow Then
KeyCode = 0 'Suppress normal effect
On Error GoTo exitsub 'ActiveControl causes a runtime error if none is active
DoCmd.GoToRecord , , acNext
elseif KeyCode = vbKeyLeftArrow Then
DoCmd.GoToRecord , , acPrevious
KeyCode = 0 'Suppress normal effect
On Error GoTo exitsub 'ActiveControl causes a runtime error if none is active


End If
exitsub:
End Sub

This doens't work of course.. help


Solution

  • You need to set the Form.KeyPreview property to True.

    Otherwise only the current control sees the keydown event.

    But note that if you have editable textboxes etc. on this form, your users may hate this behavior. They need the left/right arrow keys while editing.