【问题标题】:Compare Dates in VBA在 VBA 中比较日期
【发布时间】:2013-12-14 18:35:41
【问题描述】:

我有两个带有两个不同日期的文本框,orderDate 和 recievedDate。收到的日期需要手动输入到表单中,我想包括在 orderDate 之后应该发生的验证,我已经尝试过:

If txtRecievedDate.Text < txtOrderDate.Text Then

   MsgBox "Incorrect Date, item can't be recieved before order"

else    

  MsgBox "correct date"

End If

这不起作用,例如 RecievedDate 值为“19/11/2013”​​,OrderDate 值为“20/10/2013”​​,尽管这将是正确的日期,但此语句仅比较“19”和“20” "因此将其标记为不正确。

有没有办法在文本框中比较两个日期?为此我使用 VBA

谢谢

【问题讨论】:

  • 为什么使用文本框输入日期?见THIS

标签: vba


【解决方案1】:

以下是修复代码的方法。当然,这不是进行日期计算的最佳方法,您还必须验证 2 个文本框中是否有文本,甚至可能使用 CDate() 将文本解析为日期值,但这适用于你现在的情况。

If DateDiff("d", txtOrderDate.Text, txtRecievedDate.Text) < 0 Then

   MsgBox "Incorrect Date, item can't be recieved before order"

else    

  MsgBox "correct date"

End If

【讨论】:

    【解决方案2】:

    除了Formatting MM/DD/YYYY dates in textbox in VBA Siddharth Rout 的出色解决方案之外,我将建议以下程序。 UserForm 是 Excel 中的自然对象,但我们将引用 OCX 对象在 Access 中使用它,因此不能直接使用。

    在带有表单对象的 Access 中,可以这样做:

    Sub sof20270928CompareDates()
      If CDate(txtRecievedDate.Value) < CDate(txtOrderDate.Value) Then
        MsgBox "Incorrect Date, item can't be recieved before order"
      Else
        MsgBox "correct date"
      End If
    End Sub
    

    我们现在比较日期,而不是比较文本字符串。 CDate() 将本地日期时间字符串转换为日期类型。美国人会以 mm/dd/yyyy 格式输入日期,例如 11/19/2013,而在法国则输入 dd/mm/yyyy,例如 19/11/2013。 CDate() 将处理此问题,因为 Access 会考虑计算机的区域设置。

    另外,txtRecievedDate.Value 优先于txtRecievedDate.Text,后者需要焦点,即控件必须处于活动状态才能获取.text 属性。

    【讨论】:

      【解决方案3】:

      尝试以日期格式而不是 .text 格式比较它们

      例如

      Sub datee()
      Dim Orderdate As Date
      
      Dim Recievedate As Date
      
      Orderdate = Worksheets("Sheet1").Range("A1").Value
      Recievedate = InputBox("Enter date recieved")
      
      If Recievedate < Orderdate Then
      MsgBox "error"
      Exit Sub
      Else
      Worksheets("sheet1").Range("a3").Value = Recievedate
      End If
      
      
      End Sub
      

      【讨论】:

        【解决方案4】:

        如果您只想比较日期而不是时间,那么函数 DATEVALUE 将从日期和时间值中删除时间以便于比较。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-18
          • 1970-01-01
          相关资源
          最近更新 更多