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