Excel VBA 文本框事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19772214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:14:29  来源:igfitidea点击:

Excel VBA TextBox Events

excelvbaexcel-vba

提问by user1902849

Would like to ask expert here, why the below code doesn't work in excel sheet ? Basically this code will perform validation on input that user enter into BDTextBox, if format doesn't valid it will pop up a warning message. I've tested this code in excel sheet form and it works well however if change the textbox from form to embedded in excel sheet, it doesn't work.. any idea ?

想请教这里的高手,为什么下面的代码在excel表中不起作用?基本上,此代码将对用户输入到 BDTextBox 的输入执行验证,如果格式无效,它将弹出警告消息。我已经在 excel 表格中测试了这段代码,它运行良好,但是如果将文本框从表格更改为嵌入在 excel 表格中,它不起作用.. 知道吗?

Private Sub BDTextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If BDTextBox.Text <> "" Then
    If IsDate(BDTextBox.Text) Then
        BDTextBox.Text = Format(BDTextBox.Text, "yyyymmdd")
        FinalBusinessDate = BDTextBox.Text
    Else
        MsgBox "Please enter a valid date!" & vbNewLine & "Date format could be one of the following" & vbNewLine & "YYYY MM DD" & vbNewLine & "MM DD YYYY" & vbNewLine & "DD MM YYYY", vbCritical
        BDTextBox.Text = ""
        Cancel = True
    End If
End If
End Sub

采纳答案by Siddharth Rout

Because like Userform Textbox, there is no _ExitEvent for ActiveX Textbox embedded in the Excel Sheet. The equivalent event of _Exitis _LostFocus.

因为与用户窗体文本框一样,_ExitExcel 工作表中嵌入的 ActiveX 文本框没有事件。的等效事件_Exit_LostFocus

Try this.

尝试这个。

Private Sub BDTextBox_LostFocus()
    If BDTextBox.Text <> "" Then
        If IsDate(BDTextBox.Text) Then
            BDTextBox.Text = Format(BDTextBox.Text, "yyyymmdd")
            FinalBusinessDate = BDTextBox.Text
        Else
            MsgBox "Please enter a valid date!" & vbNewLine & _
            "Date format could be one of the following" & _
            vbNewLine & "YYYY MM DD" & vbNewLine & _
            "MM DD YYYY" & vbNewLine & "DD MM YYYY", vbCritical
            BDTextBox.Text = ""

            Cancel = True
        End If
    End If
End Sub