【问题标题】:Date Validation: Setting minimum and maximum date in a Textbox日期验证:在文本框中设置最小和最大日期
【发布时间】:2012-08-11 15:26:00
【问题描述】:

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

提前感谢您的帮助。

【问题讨论】:

    标签: validation vba date excel


    【解决方案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
    

    在大多数情况下,文本框可以设置为只接受日期,您可以设置验证规则来检查范围,因此可能不需要代码。

    【讨论】:

      【解决方案2】:

      如果您只想查看日期,可以使用 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")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多