2017-02-14 187 views
1
|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代码中,我在尝试实现上述差异时收到类型不匹配错误。请这个DateDiff并将日期汇总到日期日期

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 
+0

这是否类型不匹配时发生。无论是在价值分配还是在datediff功能? –

+1

你有'With Worksheets(“Sheet1”)'但不是所有'范围'和'Cells'在下面都是合格的,在需要的地方添加缺少的点'.'作为前缀 –

+0

它发生在:ElseIf Days = DateDiff(“ D“,StartDate,EndDate)然后 – Anthony

回答

0

帮助您使用DateDiff("D", StartDate, EndDate)StartDate是一个变量,

它应该是: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 
+0

之间的区别嗨R3uk感谢您的帮助,但运行上面的代码我现在收到类型不匹配:StartDate = .Range(“A2:A”&LastRow) – Anthony

+0

@Anthony:我的不好,我没有发现'.Value'丢失了,请尝试编辑! ;) – R3uK

+0

嗨R3uK欣赏你的时间。运行上面的代码我收到下标超出范围:如果StartDate(1,I) Anthony