简体   繁体   English

Excel VBA TextBox事件

[英]Excel VBA TextBox Events

Would like to ask expert here, why the below code doesn't work in excel sheet ? 想在这里问专家,为什么下面的代码在excel工作表中不起作用? 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. 基本上,此代码将对用户输入BDTextBox的输入执行验证,如果格式无效,则会弹出警告消息。 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表格形式测试了此代码,并且效果很好,但是,如果将文本框从表格更改为嵌入到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

Because like Userform Textbox, there is no _Exit Event for ActiveX Textbox embedded in the Excel Sheet. 因为像用户窗体文本框一样,Excel工作表中没有嵌入ActiveX文本框的_Exit事件。 The equivalent event of _Exit is _LostFocus . _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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM