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.
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.
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:
- Add a comamnd button to form
- In its properties, set its Cancel property to ‘True”
- Copy paste the below code.
- 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()
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.
- Learn more about the purpose of the “Cancel” property of a Command button.