It is possible to close a custom form by pressing any key, such as . To do this, you simply need to write code that handles the KeyDown event, explicitly identify the required key, and close the form using the Unload or End statement. The KeyDown event has two parameters: the first returns the code of the pressed key, and the second identifies the modifier key pressed. VBA has a special constant vbKeyEscape for the Escape key code. The following code, placed in the custom form’s module, closes the window when the Escape key is pressed:
Private Sub UserForm_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
If KeyCode = vbKeyEscape Then
Unload Me
End If
End Sub
Comments
- The
KeyDownandKeyUpevents occur sequentially when you press and then release a key.- The
KeyDownevent occurs when a key is pressed. - The
KeyUpevent occurs when a key is released.
- The
Syntax:
Private Sub Object_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As fmShiftState) Private Sub Object_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As fmShiftState)
These event syntaxes include the following elements:
| Element | Description |
|---|---|
Object |
Required. The name of a valid object. |
KeyCode |
Required. Integer representing the code of the pressed or released key. |
Shift |
Required. State of the Shift, Ctrl, and Alt keys. |
Table: Shift Parameter Constants
| Constant | Value | Description |
|---|---|---|
fmShiftMask |
1 | The Shift key was pressed |
fmCtrlMask |
2 | The Ctrl key was pressed |
fmAltMask |
4 | The Alt key was pressed |
You can use the following KeyCode constants anywhere in your code instead of numeric values:
| Constant | Value | Description |
|---|---|---|
vbKeyLButton |
0x1 | Left mouse button |
vbKeyRButton |
0x2 | Right mouse button |
vbKeyCancel |
0x3 | Cancel key |
vbKeyMButton |
0x4 | Middle mouse button |
vbKeyBack |
0x8 | Backspace key |
vbKeyTab |
0x9 | Tab key |
vbKeyClear |
0xC | Clear key |
vbKeyReturn |
0xD | Enter key |
vbKeyShift |
0x10 | Shift key |
vbKeyControl |
0x11 | Ctrl key |
vbKeyMenu |
0x12 | Menu key |
vbKeyPause |
0x13 | Pause key |
vbKeyCapital |
0x14 | Caps Lock key |
vbKeyEscape |
0x1B | Escape key |
vbKeySpace |
0x20 | Spacebar |
vbKeyPageUp |
0x21 | Page Up key |
vbKeyPageDown |
0x22 | Page Down key |
vbKeyEnd |
0x23 | End key |
vbKeyHome |
0x24 | Home key |
vbKeyLeft |
0x25 | Left arrow key |
vbKeyUp |
0x26 | Up arrow key |
vbKeyRight |
0x27 | Right arrow key |
vbKeyDown |
0x28 | Down arrow key |
vbKeySelect |
0x29 | Select key |
vbKeyPrint |
0x2A | Print Screen key |
vbKeyExecute |
0x2B | Execute key |
vbKeySnapshot |
0x2C | Snapshot key |
vbKeyInsert |
0x2D | Insert key |
vbKeyDelete |
0x2E | Delete key |
vbKeyHelp |
0x2F | Help key |
vbKeyNumlock |
0x90 | Num Lock key |