2012-08-15 120 views
2

我在我的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年

感謝您的幫助提前。

回答

3

你有幾個功能,您可以使用:

''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 

大多數情況下,文本框可以設置爲只接受日期,您可以設置驗證規則來檢查範圍,因此代碼可能不是必需的。

1

如果你只是要檢查的日期,你可以使用DateAdd函數來獲取日期進行比較:

'Subtract a month from today and return it as a string 
Format(DateAdd("m", -1, Now), "yyyy-mm-dd") 

'Add a year to today and return it as a string 
Format(DateAdd("yyyy", 1, Now), "yyyy-mm-dd") 
相關問題