在VBA中比较两组日期

时间:2018-10-04 16:08:23

标签: excel vba

我需要比较VBA中的两组日期(D1&D2和A1&A2)。我想知道他们在时间轴上的位置关系,并在不同条件下分配一组新的开始日期和结束日期。 我附上一张图片,以说明他们在时间轴上的可能关系以及我如何分配新日期集。

我尝试为不同的条件编写一堆“ if句子”,但是它们不能与用于获取新的A1和A2的循环一起使用。

有没有机会以更简单的方式比较这些日期?

enter image description here

我在这里添加了示例代码。谢谢!

Sub time()
  Dim D1, D2, A1, A2 As Date
  Dim N1, N2 As String
  Dim i As Integer

  For i = 1 To 4
    If A1 < D1 Then
      If A2 < D1 Then
        GoTo NextIteration
      Else
        If A2 < D2 Then
          N1 = D1
          N2 = D2
        End If
      End If
    Else
      If A1 < D2 Then
        If A2 < D2 Then
          N1 = A1
          N2 = D2
        End If
      Else
        GoTo NextIteration
      End If
    End If

NextIteration:
  Next i
End Sub

1 个答案:

答案 0 :(得分:0)

这更接近您追求的精神。显然,这些变量需要定义,而不必这样,但是逻辑应该使其余的工作更容易

sub time() 
    Dim D1 As Date, D2 As Date, A1 As Date, A2 As Date
    Dim N1 as Date, N2 As Date
    Dim i As Integer

    For i = 1 To 4
        'Doesn't take into account where A1 starts BEFORE D1 and A2 ends AFTER D2
        If A2 < D1 OR A1 > D2 Then 'occurs wholey before or after d-period
            'do nothing so the next iteration occurs without any changes
            'really you don't need this check, but it might help for debugging.
        ElseIf A1 < D1 AND A2 > D1 AND A2 < D2 Then 'intersects with d-period, but starts before
            N1 = D1 
            N2 = A2
        ElseIf A1 > D1 AND A2 < D2 Then 'occurs fully within d-period
            N1 = A1
            N2 = A2
        ElseIf A1 < D2 AND A2 > D2 Then 'intersects with d-period, but ends after
            N1 = A1
            N2 = D2
        End If
    Next i
End Sub