【VBA研究】如何检查文本框中输入的日期
发布时间
阅读量:
阅读量
iamlaosong文
在应用开发过程中,默认情况下会为文本框设置一定的验证逻辑;当用户输入的内容不满足预设条件时系统会返回错误提示信息并在相同的文本框内显示供用户再次编辑;请问具体的编程实现步骤是怎样的?
当输入为日期时,请如何验证?请考虑一个用于接收日期输入的窗体界面,在窗体内设置起止日期字段,并进行有效性验证。允许用户以八位数字的形式输入这种格式不仅便于使用,在接收到用户的数值后使用DateSerial函数将其转换为标准日期格式(例如:DateSerial(2017, 04, 31)会将错误的2017-4-31转换成2017-5-1),这样的设计既简化了操作流程又能提高数据处理效率。此外 DateSerial 这个函数非常强大 它不仅可以处理有效的年月日参数还能自动纠正一些常见的错误 如月份超出范围的情况从而确保生成的有效性

在窗口退出事件中进行日期验证,在遇到需要将错误的日期留在窗口中的情况时,请设置参数为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
AI写代码
全部评论 (0)
还没有任何评论哟~
