在VBA中比较日期

在VBA中比较日期,vba,Vba,我有两个文本框,有两个不同的日期,orderDate和ReceiveDate。接收日期需要手动输入到表单中,并且我希望包括接收数据应在orderDate之后发生的验证,我已尝试: If txtRecievedDate.Text < txtOrderDate.Text Then MsgBox "Incorrect Date, item can't be recieved before order" else MsgBox "correct date" End If

我有两个文本框,有两个不同的日期,orderDate和ReceiveDate。接收日期需要手动输入到表单中,并且我希望包括接收数据应在orderDate之后发生的验证,我已尝试:

If txtRecievedDate.Text < txtOrderDate.Text Then

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

else    

  MsgBox "correct date"

End If
如果txtReceivedDate.Text
这不起作用,例如ReceivedDate值为“19/11/2013”,OrderDate值为“20/10/2013”,尽管这将是一个正确的日期。此语句仅比较“19”和“20”,因此将其标记为不正确

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


谢谢

以下是修复代码的方法。当然,这不是进行日期计算的最佳方法,您还必须验证两个文本框中是否有文本,甚至可能使用
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
如果DateDiff(“d”,txtOrderDate.Text,txtReceivedDate.Text)小于0,则
MsgBox“日期不正确,订单前无法接收项目”
其他的
MsgBox“正确日期”
如果结束

除了在的Siddharth Rout的出色解决方案外,我还将建议以下步骤。UserForm是Excel中的一个自然对象,但我们将在Access中引用OCX对象来使用它,因此不能直接使用

在Access with form object中,可以执行以下操作:

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
Sub-sof20270928CompareDates()
如果CDate(txtReceivedDate.Value)
我们现在比较日期,而不是比较文本字符串。CDate()将本地日期时间字符串转换为日期类型。美国人会以mm/dd/yyyy格式键入日期,如2013年11月19日,而法国人则会键入dd/mm/yyyy,如2013年11月19日。CDate()将处理此问题,因为Access会考虑计算机的区域设置


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

尝试以日期格式而不是.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
Sub-datee()
Dim Orderdate作为日期
Dim ReceiveDate作为日期
Orderdate=工作表(“Sheet1”).范围(“A1”).值
ReceiveDate=输入框(“输入接收日期”)
如果ReceiveDate
如果您只想比较日期,而不想比较时间,那么该函数将从日期和时间值中删除时间,以便于比较。

为什么要使用文本框输入日期?看见