Close userform with escape button

后端 未结 4 1433
-上瘾入骨i
-上瘾入骨i 2020-12-06 06:37

I have 2 questions.

  1. When I pressed esc button then close Userform1

  2. When I input open in TextBox1

相关标签:
4条回答
  • 2020-12-06 06:45

    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
    
    0 讨论(0)
  • 2020-12-06 06:48

    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.

    0 讨论(0)
  • 2020-12-06 07:00

    Very Correct... If You Have Close Button On User Form And You Have Written Code for that ( Unload Me ) then Set Cancel Property To True ( By Default It Is False)

    0 讨论(0)
  • 2020-12-06 07:01
    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

    0 讨论(0)
提交回复
热议问题