比较日期并突出显示结果

时间:2017-06-14 09:58:36

标签: excel vba excel-vba date

我正在比较My worksheet的D和E列中的两个日期。

D列包含源日期,E列包含开始日期。

我有4个案例来比较日期。

案例1.如果日期是< 2周的开始日期,然后按时打印项目。

案例2:如果源日期是> 4周的开始日期,然后打印项目延迟。

案例3:如果源日期在开始日期的2到4周之间,则打印项目正在重新开始。

我已经为上述案例派生了代码,现在

案例4:并非每次E列都填充日期时,有时它们都是空的。

那么,我如何在这里添加一个null语句。我尝试添加一个null语句,但它失败了。

以下是代码。

Sub dateCompare()

zLastRow = Range("D" & Rows.Count).End(xlUp).Row

For r = 2 To zLastRow

    zWeeks = (Cells(r, "E") - Cells(r, "D")) / 7
    Select Case zWeeks
        Case Is > 4
            zcolour = vbRed
            Ztext = "Project Delayed " & Int(zWeeks) & " weeks"
        Case 2 To 4
            zcolour = vbYellow
            Ztext = "Project Remaining"
        Case Is < 2
            zcolour = vbGreen
            Ztext = "Project On-Time"
        Case Else
            zcolour = xlNone
            Ztext = " Check Status"
    End Select

    Cells(r, "F").Interior.Color = zcolour
    Cells(r, "F") = Ztext            
Next

End Sub

1 个答案:

答案 0 :(得分:2)

在计算zWeeks之前,请检查列&#34; E&#34; If Len(Trim(Cells(r, "E"))) = 0 Then不是空的。然后,使用您的Select Case

此外,您可以使用DateDiff函数,第一个参数为"ww"(周),直接计算列中的dats与#34; E&#34;之间的差异。 amd column&#34; D&#34;。

<强> 代码

Option Explicit

Sub dateCompare()

Dim r As Long, zLastRow As Long
Dim zWeeks As Double, zcolour As Long
Dim Ztext  As String

zLastRow = Cells(Rows.Count, "D").End(xlUp).Row

For r = 2 To zLastRow
    If Len(Trim(Cells(r, "E"))) = 0 Then ' column "E" is empty
        ' do something....
    Else ' column "E" is not empty
        zWeeks = DateDiff("ww", Cells(r, "D"), Cells(r, "E"))

        Select Case zWeeks
            Case Is > 4
                zcolour = vbRed
                Ztext = "Project Delayed " & Int(zWeeks) & " weeks"
            Case 2 To 4
                zcolour = vbYellow
                Ztext = "Project Remaining"
            Case Is < 2
                zcolour = vbGreen
                Ztext = "Project On-Time"
            Case Else
                zcolour = xlNone
                Ztext = " Check Status"
        End Select

        Cells(r, "F").Interior.Color = zcolour
        Cells(r, "F") = Ztext
    End If
Next r

End Sub