Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close userform with escape button

Tags:

excel

vba

I have 2 questions.

  1. When I pressed esc button then close Userform1

  2. When I input open in TextBox1 then Userform2 should show. Also clear TextBox1 in Userform1 automatically.

I have tried the below code:

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If textbox1.value = "open" then
        userform2.show
        textbox1.value =""
    End If
End Sub
like image 679
Tomz Avatar asked Nov 27 '13 11:11

Tomz


3 Answers

Close userform1 with Esc

If you don't have any controls on userform then simply use this code

Private Sub UserForm_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii = 27 Then Unload Me
End Sub

If you have say a TextBox and a Command Button then use this

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

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii = 27 Then Unload Me
End Sub

Private Sub UserForm_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii = 27 Then Unload Me
End Sub

Private Sub CommandButton1_Click()
    Unload Me
End Sub

If you have any other control that can take focus then you will have to use the KeyPress event of that control like I did for TextBox

when I input "open" to textbox1 then userform2 showed also clear textbox1 in userform1 automatically.

KeyPress will capture only one key. Use the Change event to compare what is there in the textbox.

Private Sub TextBox1_Change()
    If LCase(TextBox1.Value) = "open" Then
        TextBox1.Value = ""
        UserForm2.Show
    End If
End Sub
like image 195
Siddharth Rout Avatar answered Nov 11 '22 00:11

Siddharth Rout


  1. Insert a new Command Button
  2. Switch its Cancel property to True
  3. You May Name it as cmdClose
  4. Add next code:

    Private Sub cmdClose_Click()
    
        Unload Me
    
    End Sub
    

5.Set height and widht of the button to 0

that's it

like image 26
Jesus Avatar answered Nov 11 '22 00:11

Jesus


if you have a button the closes the form, just set the (Cancel) property to True and that will fire the cancel button on (Esc).. Cheers.

like image 23
Mahmoud Sayed Avatar answered Nov 11 '22 00:11

Mahmoud Sayed