Reputation: 552
Columns A, D and E are date and time.
I am trying to find out how many times the date in Column A falls between the start dates and end dates.
Column A may vary between 30 and 60 days while the start and end dates run to thousands.
Two questions:
Code:
Option Explicit
Sub DaysCount()
Dim endRow As Long
Dim LastRow As Long
Dim ICount As Long
Dim Day() As Variant
Dim StartDate() As Variant
Dim EndDate() As Variant
ICount = 0
With ThisWorkbook.Worksheets("sheet1")
LastRow = .Range("A" & .Rows.count).End(xlUp).Row
endRow = .Range("D" & .Rows.count).End(xlUp).Row
Day = Sheet1.Range("A2:A" & LastRow)
StartDate = Sheet1.Range("D2:D" & endRow)
EndDate = Sheet1.Range("E2:E" & endRow)
For i = LBound(StartDate) To UBound(StartDate)
For J = LBound(Day) To UBound(Day)
If Day(J, 1) >= StartDate(i, 1) And Day(J, 1) <= EndDate(i, 1) Then
ICount = ICount + 1
Else
End If
Sheet1.Range("B" & J).Value = ICount
Next i
ICount = 0
Next J
End With
End Sub
Upvotes: 1
Views: 1711
Reputation: 14547
Option Explicit
forces you to declare all variables, so you need to declare i
and j
too.
And your Next i
and Next j
weren't in the good order!
VBA : DateAdd("d",.Range("A3"),1)
Corrected code:
Option Explicit
Sub DaysCount()
Dim i As Long
Dim j As Long
Dim endRow As Long
Dim LastRow As Long
Dim ICount As Long
Dim Day() As Variant
Dim StartDate() As Variant
Dim EndDate() As Variant
ICount = 0
With ThisWorkbook.Worksheets("sheet1")
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
endRow = .Range("D" & .Rows.Count).End(xlUp).Row
Day = Sheet1.Range("A2:A" & LastRow)
StartDate = Sheet1.Range("D2:D" & endRow)
EndDate = Sheet1.Range("E2:E" & endRow)
For i = LBound(Day) To UBound(Day)
For j = LBound(StartDate) To UBound(StartDate)
If Day(j, 1) >= StartDate(i, 1) And Day(j, 1) <= EndDate(i, 1) Then
ICount = ICount + 1
Else
End If
Next j
.Range("B" & i).Value = ICount
ICount = 0
Next i
End With
End Sub
Upvotes: 2