iamlaosong文
应用中经常会对文本框的输入内容进行检查,如果不符合要求,给出提示,保留在文本框中重新输入,如何编程?
如果输入的是日期,如何检查?下面是一个输入日期的窗体,输入起止日期并进行检查,输入用8位数字,这样输入比较快,输入后用DateSerial转换成日期格式(DateSerial是个很有意思的函数,其功能是将参数年月日转换成一个有效的日期。虽然要求输入规范的年月日,不过,输入不规范也没关系,它可以将输入不规范的日期,转换成规范的日期,DateSerial(2017,04,31)转换成2017-5-1),界面如下图:

用文本框退出事件对日期进行检查,当日期有误需要留在文本框中时,令参数cancel=True即可,代码如下:
'输入日期,确定按钮
Private Sub CommandButton1_Click()
StartDate = TextBox1.Value
EndDate = TextBox2.Value
TextBox1.Value = ""
TextBox2.Value = ""
Input_Date.Hide
End Sub
'输入日期,取消按钮
Private Sub CommandButton2_Click()
TextBox1.Value = ""
TextBox2.Value = ""
StartDate = ""
EndDate = ""
Input_Date.Hide
End Sub
'输入日期,初始化文本框
Private Sub TextBox1_Enter()
If TextBox1.Value = "" Then TextBox1.Value = Format(Date, "yyyymmdd")
End Sub
'输入日期,离开起始日期
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox1.Value Like "########" Then
TextBox2.Value = TextBox1.Value
TextBox1.Value = DateSerial(Left(TextBox1.Value, 4), Mid(TextBox1.Value, 5, 2), Right(TextBox1.Value, 2))
Else
'日期有误,留在输入框
MsgBox "日期有误,请重新输入!", vbOKOnly, "iamlaosong"
TextBox1.Value = Format(Date, "yyyymmdd")
Cancel = True
End If
End Sub
'输入日期,离开截止日期
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox2.Value Like "########" Then
TextBox2.Value = DateSerial(Left(TextBox2.Value, 4), Mid(TextBox2.Value, 5, 2), Right(TextBox2.Value, 2))
If TextBox2.Value < TextBox1.Value Then
MsgBox "截止日期不能小于起始日期!", vbOKOnly, "iamlaosong"
Cancel = True
End If
Else
MsgBox "日期有误,请重新输入!", vbOKOnly, "iamlaosong"
TextBox2.Value = Format(TextBox1.Value, "yyyymmdd")
Cancel = True
End If
End Sub