Search code examples
exceluserformvba

Close userform with Esc without control_KeyPress() command for each control


In this answer, it's shown that Excel userforms can be closed with Esc by setting up a control_KeyPress() sub for each control that can take focus - Close userform with escape button

I've gotten this to work, but I have several menus, each with a number of controls. I tried putting this routine on just one button, but it's not always quick to tab/nav back to a specific button.

I'm looking for a way to make it so that I either

  1. don't have to create control_KeyPress() subs for every control that can take focus
  2. or, can achieve the same goal (closing the userform with esc) in a different way

Thanks!


Solution

  • My idea would be to create a command button on the form, set the cancel property to true AND set the width and height to 0. Add the following code to the not visible button.

    Private Sub CommandButton1_Click()
        Hide
    End Sub
    

    Leave the visible property on true

    enter image description here