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.
- 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
'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:
- Learn more about the purpose of the "Cancel" property of a Command button.