比较日期与案例和Datedifference方法

时间:2017-07-10 13:35:58

标签: excel vba excel-vba

我有一张名为Result的表格。

在这张表中,我在第一列中列出了带有s.Date和开始日期的列H.

列H完全填满,第I列有时会出现空行。

我的案件如下所述,

案例1。如果开始日期是> 4个星期的S.Date然后它是准时并且突出显示为绿色

case2:如果开始日期是>然后是S.Date的8周,这是延迟。

案例3:如果开始日期在4到8周之间,那么它是剩余的,它是黄色的。

案例4:开始日期早于S.date,在这种情况下也应该是绿色。

以上三个案例都已实现,但我很震惊如何实现第四个案例。 任何人都可以建议,我怎么做。附有图片也供参考。我已经发布了这个,但没有积极的回复或聊天来澄清我的疑问。很抱歉转发,但我想澄清这个问题。期待论坛的帮助。

Option Explicit

Sub status()
    Dim ws As Worksheet
    Dim lrow As Long, i As Long
    Dim zWeeks As Double, zcolour As Long
    Dim Ztext As String
    Set ws = Sheets("Result")
    With ws
        lrow = .Range("H" & .Rows.Count).End(xlUp).Row
        For i = 5 To lrow
            zWeeks = DateDiff("ww", .Range("I" & i).Value, .Range("H" & i).Value)
            If .Range("E" & i).Value <> "" And .Range("F" & i).Value <> "" And .Range("I" & i).Value = "" Then
                Ztext = "remaining"
                zcolour = vbYellow
                Cells(i, 11) = "Yellow"
            ElseIf .Range("F" & i).Value = "" And .Range("I" & i).Value = "" Then
                GoTo nextrow
            ElseIf zWeeks < 4 Then
                Ztext = "  on time"
                zcolour = vbGreen
                Cells(i, 11) = "Green"
            ElseIf zWeeks > 8 Then
                Ztext = " delayed"
                zcolour = vbRed
                Cells(i, 11) = "Red"
            ElseIf zWeeks > 4 < 8 Then
                Ztext = "Remaining"
                zcolour = vbYellow
                Cells(i, 11) = "Yellow"
            End If
            With .Range("J" & i)
                .Value = Ztext
                .Interior.Color = zcolour
            End With
nextrow:
        Next i
    End With
End Sub

The Image below Shows the result that is needed. Could someone help to achieve the last case, as mentioned.

1 个答案:

答案 0 :(得分:0)

据我所知,案例4应该从上面返回一个负值,所以你可以使用如下的条件 再添加一个公式

zdays = DateDiff("d", .Range("I" & i).Value, .Range("H" & i).Value) '**Checknotes below

elseif zweeks < 0 or zdays < 0 or zdays = 0 then
   Cells(i, 11) = "Green"
End if

**注: 1. zdays将在同一周内处理日期 2.这将返回负值