比较日期时类型不匹配错误

时间:2017-03-21 12:35:10

标签: excel vba

此代码第二次通过For Next Loop产生类型不匹配错误。我不知道为什么。

    Dim HD As Integer
    Dim HireDate2 As Date
    Dim HireDate3 As Integer
    Dim today As Date
    today = Now()
    HD = 2
    For HD = 2 To HireDate
        HireDate2 = Range("Z2:Z" & HD)
        MsgBox "Hire Date is " & HireDate2
       If (HireDate2 > today) Then
            HireDate3 = HireDate3 + 1
        End If
        HD = HD + 1
    Next HD

提前感谢您的帮助

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

Dim HD As Long
Dim HireDate2 As Date
Dim HireDate3 As Long
Dim MyToday As Date
Dim HireDate As Long

MyToday = Date  ' <-- get today's date into a variable

For HD = 2 To HireDate
    HireDate2 = Range("Z" & HD).Value
    MsgBox "Hire Date is " & HireDate2
    If DateDiff("d", MyToday, HireDate2) > 0 Then ' <-- if HireDate 2 is in the future
        HireDate3 = HireDate3 + 1
    End If
Next HD