我的 VBA 代码中有一个函数,可以为文本框设置特定的日期格式。
这是我的代码,用于验证日期的格式是否正确:
Function CheckDate(DateStg As String) As Boolean
If DateStg = "" Then
' Accept an empty value in case user has accidentally moved to a new row
CheckDate = True
lblMessage.Caption = ""
Exit Function
End If
If IsDate(DateStg) Then
CheckDate = True
lblMessage.Caption = ""
Else
CheckDate = False
lblMessage.Caption = "Sorry I am unable to recognise " & DateStg & " as a date."
End If
End Function
除了检查文本框中的日期是否是实际日期之外,我还需要验证文本框日期是否不小于当前日期减去 1 个月,并且。另外,我想验证该日期是否不超过当前日期加 1 年。
所以:
- DateStg > 今天 - 1 个月
- DateStg < 今天 + 1 年
感谢您提前提供的帮助。
最佳答案
您可以使用一些功能:
''Assume date is not good
DateOK=False
If IsDate(DateStg) Then
If DateStg > dateAdd("m",-1,Date()) _
And DateStg < dateAdd("m",12,Date()) Then
''Date is good
DateOK=True
End If
End if
在大多数情况下,文本框可以设置为仅接受日期,并且您可以设置验证规则来检查范围,因此可能不需要代码。
关于validation - 日期验证 : Setting minimum and maximum date in a Textbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11967520/