2013-02-18 76 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" 

結束如果