Excel VBA文本框事件

想问问这里的专家,为什么下面的代码在excel表格中不起作用? 基本上这个代码会对用户input到BDTextBox的input进行validation,如果格式不合法,它会popup一个警告消息。 我已经在Excel表单中testing了这个代码,并且它工作正常,但是如果将表单中的文本框从表单中更改为embedded到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 

因为像Userform Textbox一样,Excel Sheet中没有embeddedActiveX Textbox的_Exit Event。 _Exit的等价事件是_LostFocus

尝试这个。

 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