KeyDown, KeyUp events

Occur in sequence when a user presses and releases a key. KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.

Syntax

Private Subobject _KeyDown( ByValKeyCodeAs MSForms.ReturnInteger, ByValShiftAs fmShiftState)
Private Subobject _KeyUp( ByValKeyCodeAs MSForms.ReturnInteger, ByValShiftAs fmShiftState)

The KeyDown and KeyUp event syntaxes have these parts:

Part Description
object Required. A valid object name.
KeyCode Required. An integer that represents the key code of the key that was pressed or released.
Shift Required. The state of SHIFT, CTRL, and ALT.

Settings

The settings for Shift are:

Constant Value Description
fmShiftMask 1 SHIFT was pressed.
fmCtrlMask 2 CTRL was pressed.
fmAltMask 4 ALT was pressed.

Remarks

The KeyDown event occurs when the user presses a key on a running form while that form or a control on it has the focus. The KeyDown and KeyPress events alternate repeatedly until the user releases the key, at which time the KeyUp event occurs. The form or control with the focus receives all keystrokes. A form can have the focus only if it has no controls or all its visible controls are disabled.

These events also occur if you send a keystroke to a form or control by using either the SendKeys action in a macro or the SendKeys statement in Visual Basic.

The KeyDown and KeyUp events are typically used to recognize or distinguish between:

  • Extended character keys, such as function keys.

  • Navigation keys, such as HOME, END, PAGEUP, PAGEDOWN, UP ARROW, DOWN ARROW, RIGHT ARROW, LEFT ARROW, and TAB.

  • Combinations of keys and standard keyboard modifiers (SHIFT, CTRL, or ALT).

  • The numeric keypad and keyboard number keys.

The KeyDown and KeyUp events don't occur under the following circumstances:

  • The user presses Enter on a form with a command button whose Default property is set to True.

  • The user presses Esc on a form with a command button whose Cancel property is set to True.

The KeyDown and KeyPress events occur when you press or send an ANSI key. The KeyUp event occurs after any event for a control caused by pressing or sending the key. If a keystroke causes the focus to move from one control to another control, the KeyDown event occurs for the first control, while the KeyPress and KeyUp events occur for the second control.

The sequence of keyboard-related events is:

  1. KeyDown
  2. KeyPress
  3. KeyUp

Note

The KeyDown and KeyUp events apply only to forms and controls on a form. To interpret ANSI characters or to find out the ANSI character corresponding to the key pressed, use the KeyPress event.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.