Following code, I wrote after a lot of research and hard work however I now found this is of no use as I have multiple filters in the worksheetsheet. I do not want to loop through all the data in the sheet, I want to loop through only the data that are visible when filtered. But, with my code it loops through all the rows. At a time I have up to 5 columns filtered.
In dt = CDate(Sheets("Sheet5").Range("P2").Value) I have given P2 but when I filter it might not be visible and I do not want to check data in this cell.
Sub FindDuration()
Dim totalDuration As Single
Dim dt As Date
Dim nextDt As Date
Dim maxDt As Date
Dim DateDiff
Dim lr As Long
Dim lrw As Long
Dim lr1 As Long
Dim i As Long
totalDuration = 0
dt = 0
lr1 = ThisWorkbook.Sheets("Sheet5").Range("A" & Rows.Count).End(xlUp).Row
dt = CDate(Sheets("Sheet5").Range("P2").Value)
maxDt = dt + 1
For i = 2 To lr1
DateDiff = maxDt - dt
If DateDiff <= 1 And nextDt <= maxDt Then
totalDuration = totalDuration + Sheets("Sheet5").Range("G" & i).Value
nextDt = CDate(Sheets("Sheet5").Range("P" & i + 1).Value)
Else
lrw = ThisWorkbook.Sheets("Chart").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Chart").Range("A" & lrw + 1).Value = totalDuration
totalDuration = Sheets("Sheet5").Range("G" & i).Value
dt = CDate(Sheets("Sheet5").Range("P" & i).Value)
maxDt = dt + 1
End If
Next i
lrw = ThisWorkbook.Sheets("Chart").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Chart").Range("A" & lrw + 1).Value = totalDuration
End Sub
I know this code is not perfect because I am not an expert in VBA.
Edit:
What you can see in the image below is just sample data. Value in the Columns J and K (in our code G and P) is what we have L, N, O is what we want. We have almost accomplished 'Total Duration to add' with our code and with columns N and O is where I have the issue.
