2013-02-18 75 views
-1

试图创建一个函数来比较VBA中的两个日期(需要日期&订单日期), 如果需要的日期早于订单日期,则应该会产生错误。日期函数VBA

+0

尝试'datediff' :)如果你有日期变量,那么你就可以直接比较。日期如何传递给函数? – 2013-02-18 17:41:00

+6

我们可以安全地假设你自己什么都没有尝试过吗? – mwolfe02 2013-02-18 17:41:45

+0

并非完全,我做了一些事情,但在一个漫长的过程中首先确保字符串被存储为日期使用CDate。然后我不能将它们与所需日期早于订单日期的标准进行比较,那么应该出现错误消息。 – Cesar 2013-02-18 17:49:37

回答

0

试试这个

If dateRequired < orderDate Then 
    Debug.Print "this should generate an error." 
End If 
3

而且我的第一个评论,这里有四个例子的日期比较

'~~> Direct Date Comparision 
Sub Sample1() 
    Dim dt1 As Date, dt2 As Date 

    dt1 = #12/12/2014# 
    dt2 = #12/12/2013# 

    Debug.Print IsGreater(dt1, dt2) 
End Sub 

'~~> Converting string to date and directly comparing 
Sub Sample2() 
    Dim dt1 As String, dt2 As String 

    dt1 = "12/12/2014" 
    dt2 = "12/12/2013" 

    Debug.Print IsGreater(CDate(dt1), CDate(dt2)) 
End Sub 

'~~> Using DateDiff with direct date comparision 
Sub Sample3() 
    Dim dt1 As Date, dt2 As Date 

    dt1 = #12/12/2014# 
    dt2 = #12/12/2013# 

    If DateDiff("d", dt2, dt1) > 0 Then 
     MsgBox "Greater" 
    Else 
     MsgBox "Smaller or Equal" 
    End If 
End Sub 

'~~> Using DateDiff with converting string to date and directly comparing 
Sub Sample4() 
    Dim dt1 As Date, dt2 As Date 

    dt1 = "12/12/2014" 
    dt2 = "12/12/2013" 

    If DateDiff("d", CDate(dt2), CDate(dt1)) > 0 Then 
     MsgBox "Greater" 
    Else 
     MsgBox "Smaller or Equal" 
    End If 
End Sub 

Function IsGreater(d1 As Date, d2 As Date) As Boolean 
    IsGreater = d1 > d2 
End Function 
+0

很好,系统的答案 - +1 – 2013-02-18 19:45:52

0

昏暗的订购日期截止日期

昏暗earlierdate截止日期

订购日期= InputBox(“输入订单日期”)

earlierdate = “12/12/2011”

如果订购日期> earlierdate然后

MsgBox "Error" 

结束如果