使用转义按钮关闭userform

Tom*_*omz 8 excel vba excel-vba

我有两个问题.

  1. 当我按下esc按钮然后关闭Userform1

  2. 当我输入openTextBox1Userform2应该显示.还清楚TextBox1Userform1自动.

我试过以下代码:

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If textbox1.value = "open" then
        userform2.show
        textbox1.value =""
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

Sid*_*out 18

关闭userform1 Esc

如果您对userform没有任何控制,那么只需使用此代码即可

Private Sub UserForm_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii = 27 Then Unload Me
End Sub
Run Code Online (Sandbox Code Playgroud)

如果你说一个TextBox和一个命令按钮,那么使用它

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
Run Code Online (Sandbox Code Playgroud)

如果你有任何其他控件可以成为焦点,那么你将不得不KeyPress像我一样使用该控件的事件TextBox

当我向textbox1输入"open"时,userform2会自动在userform1中显示清晰的textbox1.

KeyPress将仅捕获一个键.使用该Change事件来比较文本框中的内容.

Private Sub TextBox1_Change()
    If LCase(TextBox1.Value) = "open" Then
        TextBox1.Value = ""
        UserForm2.Show
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法实现这一点,而无需为每个可以关注的按钮创建KeyPress子?我有一个userform,上面有很多控件,我希望能够在任何时候使用Esc卸载表单. (2认同)

Jes*_*sus 17

  1. 插入一个新的命令按钮
  2. 将其Cancel属性切换为True
  3. 您可以将其命名为cmdClose
  4. 添加下一个代码:

    Private Sub cmdClose_Click()
    
        Unload Me
    
    End Sub
    
    Run Code Online (Sandbox Code Playgroud)

5.将按钮的高度和宽度设置为0

而已

  • 确保新按钮是唯一一个 Cancel 属性设置为 True 的按钮。 (2认同)
  • 还可以考虑将此按钮的 `TabStop` 属性设置为 `False` 以从键盘的 Tab 循环中删除该按钮。 (2认同)