DateDiff和总结日期到日期日历

时间:2017-02-14 11:40:51

标签: excel vba excel-vba

|Start Date |End Date |Diff|
|15-Feb-17  |16-Feb-17| 2  |
|13-Feb-17  |13-Feb-17| 1  |
|13-Feb-17  |14-Feb-17| 2  |
|01-Feb-17  |10-Feb-17| 1  | '(When dates are like this then the difference = 1)
|15-Jan-17  |15-Feb-17| 3  | '(This = Difference between End Date and First date in 'the calendar)  

在下面的VBA代码中,我尝试实现上述差异时收到类型不匹配错误。请协助这个

Sub OnRentCounter()
    Dim lastRow As Long
    Dim StartDate() As Variant
    Dim Date1 As Date
    Dim EndDate As Date
    Dim Days As Single

    With Worksheets("Sheet1")
        'Determine last Row in Column A
         lastRow = Sheet1.Range("B999999").End(xlUp).Row
         Date1 = Cells(2, 6).Value
         'Calculate Difference between Start Date And End Date in Days
         StartDate = Range("A2:A" & lastRow)
         For i = LBound(StartDate) To UBound(StartDate)
             EndDate = Cells(2, i).Value
             If StartDate(1, i) < Date1 Then
                 Days = DateDiff("D", Date1, EndDate)
                 Days = Days + 1
                 Cells(i + 1, 3) = Days
                 Days = 0
             ElseIf EndDate < Date1 Then
                     Days = DateDiff("D", Date1, Date1)
                     Days = Days + 1
                     Cells(i + 1, 3) = Days
                     Days = 0
             ElseIf Days = DateDiff("D", StartDate, EndDate) Then
                 Days = Days + 1
                 Cells(i + 1, 3) = Days
                 Days = 0
             End If
         Next i
     End With
 End Sub

1 个答案:

答案 0 :(得分:0)

您使用的是DateDiff("D", StartDate, EndDate),但StartDate是Variant,

应该是:DateDiff("d", StartDate(i, 1), EndDate)

Sub OnRentCounter()
    Dim LastRow As Long
    Dim StartDate() As Variant
    Dim Date1 As Date
    Dim EndDate As Date
    Dim Days As Single

    With Worksheets("Sheet1")
        'Determine last Row in Column A
         LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
         Date1 = .Cells(2, 6).Value
         'Calculate Difference between Start Date And End Date in Days
         StartDate = .Range("A2:A" & LastRow).Value
         For i = LBound(StartDate, 1) To UBound(StartDate, 1)
             EndDate = .Cells(2, i).Value

             Debug.Print Format(StartDate(i, 1),"dd-MMM-yy")
             Debug.Print Format(EndDate,"dd-MMM-yy")
             Debug.Print Format(Date1,"dd-MMM-yy")


             If StartDate(i, 1) < Date1 Then
                 Days = DateDiff("d", Date1, EndDate)
             ElseIf EndDate < Date1 Then
                 Days = DateDiff("d", Date1, Date1)
             ElseIf Days = DateDiff("d", StartDate(i, 1), EndDate) Then

             End If
             .Cells(i + 1, 3) = Days + 1
             Days = 0
         Next i
     End With
 End Sub