VBA - 使用 ESC 关闭时 TextBox_Exit 无法正常工作

问题描述 投票:0回答:3

我有一个带有

TextBox1
CommandButton1
的表格。

Cancel
CommandButton1
属性是
True
。这样我就可以通过按
Esc
来关闭表单。

TextBox1
有一个 Exit 事件,所以当离开这个元素时会触发一个事件。在这种情况下,我将打印用户输入和一些静态内容。

Sub CommandButton1_Click()
    Unload Me
End Sub

Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Debug.Print "Textbox1_Exit was fired, content was: " & TextBox1.Value
End Sub

现在我在

TextBox1
中输入一些内容,假设我输入“foo”。

如果我用

CommandButton1
关闭表单,输出将是:

TextBox1_Exit 被触发,内容为:foo

问题: 如果我通过

Esc
键离开表单,输出将仅为:

TextBox1_Exit 被触发,内容为:

因此只会打印

Debug.Print
的静态部分。 我想在这两种情况下获得用户输入。

vba textbox exit
3个回答
1
投票

好吧,这有点棘手 - 因为在用户表单中使用

TextBox1.Value
时您无法获取
Esc
,所以您可以使用
Public
字符串变量来模拟
TextBox
中的条目。因此,您需要声明一个
Public
变量,添加一个
TextBox_Change
事件,并添加一个
Userform_Initialize
事件来每次重置字符串:

Public mystring As String
Sub CommandButton1_Click()
    Unload Me
End Sub

Private Sub TextBox1_Change()

If Not Len(TextBox1.Value) <= Len(mystring) + 1 Then
    mystring = mystring & Right(TextBox1.Value, 1)
Else
    If TextBox1.Value <> "" Then
        mystring = TextBox1.Value
    End If
End If

End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Debug.Print "Textbox_Exit was fired, content was: " & mystring
End Sub

Private Sub UserForm_Initialize()
    mystring = ""
End Sub

0
投票

您可以使用

UserForm_QueryClose
事件捕获
UserForm
退出事件并调用
TextBox1_Exit
一:

Option Explicit

Sub CommandButton1_Click()
    Unload Me
End Sub

Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Debug.Print "Textbox1_Exit was fired, content was: " & TextBox1.Value
End Sub


Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    Dim myVar As MSForms.ReturnBoolean
    Me.TextBox1_Exit myVar
End Sub

0
投票

一种解决方案是取消文本框中的转义键。

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    ' Prevent escape from deleting the text in the textbox
    If KeyCode = 27 Then
        KeyCode = 0
        ' Type code here for pressing the button bound to escape / closing the form 
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.