VBA Userform – Escape key to Close – Unload form

Make VBA Userform to Close with Escape Key

Usually developers add a command button to close or exit a userform.

Sometimes, if the end user is going to close the form and load it very frequently, It is good to provide a keyboard shortcut to close userform.The defacto key for close a userform is “Escape” key.

Lets see how to map a Escape key to Close/Exit button in userform.

Map Command buttond & Close Userform using Escape Key

By default there is a property available for all command button controls. This is called “Cancel” which can be found on properties window as in this image.

VBA-VB6 Close Userform with Escape Key
VBA-VB6 Close Userform with Escape Key

The purpose of this property is to capture the escape key press and forward it to the click event of the specific command button.

Here is how we can implement this in your VBA project:

  1. Add a comamnd button to form
  2. In its properties, set its Cancel property to ‘True”
  3. Copy paste the below code.
  4. Run form with F5 & press Esc key

Note: If you already have a command button added with name close, then skip step1.

'Code for command button to close userform with escape key
Private Sub CommandButton1_Click()
    Unload Me
    'or
    'Me.Hide
End Sub

This is the easiest method to map a esc key to a comamnd button control. There are others ways as well – by capturing the key press events & filter out the escape key (ASCII code 27) and then take appropriate action.

But, still this methods is straight forward & optimal.

External References: