Excel/Number of rows between values
In column A, I have a list of time values(8:00,8:01,8:02 etc). Duplicate times can appear in this column (8:00.8:01,8:01,8:02)As an example, I need to count the number of rows between 8:00 and 8:10. I tried a matching formula but time values and matching formulas are unreliable. Any suggestions?
Yes, the matching formula is unreliable because it looks a the internal representations of time values rather than what is displayed. For example, when you see 8:00 displayed, this is actually internally 0.333333333..., or 1/3 of a day since internally times are represented as fractions of days. Since matches must be exact, the fact that Excel cannot represent 1/3 exactly causes this problem.
Here is a user-defined function (UDF) that gets around this problem by only requiring that the time match within 0.1 second. Here is the code:
Function RowsBetween(R1 As Range, Tstart As String, Tstop As String) As Long
' Gives number of rows between time values located starting in range T1,
' and starting at time value Tstart and ending at Tstop.
' Example: =RowsBetween( A1, "8:00", "8:10" ) will give the number of rows
' between 8:00 and 8:10 in column A.
Dim iRow As Long
Dim Row1 As Long
Dim Row2 As Long
Dim T1 As Date
Dim T2 As Date
'Convert time strings to date values
T1 = TimeValue(Tstart)
T2 = TimeValue(Tstop)
iRow = R1.Row
Row1 = iRow
Do Until IsEmpty(Cells(iRow, R1.Column))
If ApproxEquals(Cells(iRow, R1.Column), T1) Then
Row1 = iRow
ElseIf ApproxEquals(Cells(iRow, R1.Column), T2) Then
Row2 = iRow
RowsBetween = Row2 - Row1
iRow = iRow + 1
Function ApproxEquals(T1 As Date, T2 As Date) As Boolean
'tests two date-time values and returns True if they
'are the same within 0.1 second
ApproxEquals = Abs(T2 - T1) < 0.1 / 86400
Please note that the start and end times must be entered as text strings (i.e., in quotes),
and that R1 identifies the column containing the time values, but more specifically the cell
where the search starts.
1. If as you mention that there are two or more successive values it will count rows between the last starting value and the first ending value. For example, if your list is (8:00, 8:00, 8:00, 8:01, ..., 8:09, 8:10, 8:10)), RowsBetween will still give a number of rows = 10.
2. You don't want to include the starting row in the count.
To install this UDF in your workbook:
1. Go to the Visual Basic Editor (keyboard Alt-TMV)
2. Insert a new macro module (Alt-IM)
3. Paste all the above code into the Code pane.
The UDF will then be immediately available for use. Use it as illustrated by the example in the
I hope you find this helpful.