Link to home
Start Free TrialLog in
Avatar of kcooke2424
kcooke2424

asked on

Excel VBA Userform Controls Question

I have created a userform in Excel VBA, and on that userform is a "Quit" button. In the event handler for the Quit button, I have coded for a message box to appear asking the user "Are you sure you want to quit?" How can I make it so that pressing the Escape key is equivalent to clicking on the Quit button? (When I press Escape, I want the message box to pop up)
Avatar of zorvek (Kevin Jones)
zorvek (Kevin Jones)
Flag of United States of America image

Set the command button's Cancel property to True.

Kevin
Avatar of kcooke2424
kcooke2424

ASKER

Is there a way to make Escape perform the same event handler routine as the Quit button?
ASKER CERTIFIED SOLUTION
Avatar of zorvek (Kevin Jones)
zorvek (Kevin Jones)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
kcooke2424,

You will most likely need to set it up as in the attached file - see code below.

Patrick
In UserForm1 VBA code pane:

Private Sub UserForm_Initialize()
Me.CommandButton1.Cancel = True
End Sub

Private Sub CommandButton1_Click()
Unload UserForm1
End Sub

Open in new window

Userform-cancel-01.xls
kcooke2424,

I should have read your requirements more carefully. The code below allows the user to continue even after pressing the ESC button - if so required.

It's in the attached file.

Patrick
Private Sub UserForm_Initialize()
Me.CommandButton1.Cancel = True
End Sub

Private Sub CommandButton1_Click()
Dim Msg, Style, Title, Response
Msg = "Are you sure you want to quit?"    ' Define message.
Style = vbYesNo + vbCritical + vbDefaultButton2    ' Define buttons.
Title = "Quit?"    ' Define title.
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
    Unload UserForm1
End If

End Sub

Open in new window

Userform-cancel-02.xls
The answer to the question:

"How can I make it so that pressing the Escape key is equivalent to clicking on the Quit button?"

is:

"Open the user form in the editor, select the "Quit" command button, press F4, locate the "Cancel" property and set it to True. This will invoke the Quit button when the user presses ESCAPE."

The asker stated in the question that he already had written the event handler with the message box and so did not need an event handler written.

Kevin