excelexcel-formula

Excel - Formula to extract total time above a specific temperature


I have 100 files, each about 30K lines of data like this:

enter image description here

As shown, the instances are not sequential. I wonder if I can write a formula capable of looking at all instances >0°F, then look at the date/time and add the total time in hrs. It was above that temperature.

I've tried index/match, xlookup, but nothing more streamlined to my problem. What I've tried required a lot of formulas but only adding them manually by segment, not a formula capable of adding a total of n segments.

For this example, the result is 4.1 hours, which was calculated adding the total for each segment found (2) the first is 2.3 hrs (from 9:26:14 - 11:41:14) the second is 1.8 hrs (from 12:01:14 - 13:51:14).


Solution

  • Option with REDUCE:

    =LET(
        input, B2:D30000,
        dtime, LAMBDA(i, INDEX(input, i, 1) + INDEX(input, i, 2)),
        val, LAMBDA(i, INDEX(input, i, 3)),
        total_intervals, REDUCE(
            0,
            SEQUENCE(ROWS(input)),
            LAMBDA(acc, cur,
                acc +
                    IF(
                        OR(cur = 1, val(cur) <= 0, val(cur - 1) <= 0),
                        0,
                        dtime(cur) - dtime(cur - 1)
                    )
            )
        ),
        VSTACK(
            "Total time for all instances > 0°F",
            TEXT(total_intervals, "[h]""h"" mm""m""")
        )
    )
    

    Result with REDUCE

    With Named Function

    Named Function

    To make it easier to apply the formula with multiple inputs, we could define a named function with:

    =LAMBDA(input, LET(dtime, LAMBDA(i, INDEX(input, i, 1) + INDEX(input, i, 2)), 
    val, LAMBDA(i, INDEX(input, i, 3)), 
    REDUCE(0, SEQUENCE(ROWS(input)), LAMBDA(acc,cur, acc 
    + IF(OR(cur = 1, val(cur) <= 0, val(cur - 1) <= 0), 0, dtime(cur) - dtime(cur - 1)))) * 24))
    

    then apply with different ranges

    =totalHoursForAboveZero('path[filname]sheet'!range)
    
    or 
    
    =totalHoursForAboveZero(B2:D30000)
    

    Result


    Adding formula via VBA

    Just a quick suggestion to set the formula only - you can fit it into another routine for adding into multiple files.

    Sub InsertTotalTimeFormula()
    
        part1 = "=LAMBDA(input, LET(dtime, LAMBDA(i, INDEX(input, i, 1) + INDEX(input, i, 2)), val, LAMBDA(i, INDEX(input, i, 3)), total_intervals, REDUCE(0, SEQUENCE(ROWS(input)), "
        part2 = "LAMBDA(acc,cur, acc + IF(OR(cur = 1, val(cur) <= 0, val(cur - 1) <= 0), 0, dtime(cur) - dtime(cur - 1)))), VSTACK(""Total time for all instances > 0°F"", TEXT(total_intervals,  ""[h]\h mm\m""))))"
        inputRange = "(B2:D30000)"
        
        With ActiveWorkbook.ActiveSheet
            Range("H4").Select
            Selection.Formula2 = part1 & part2 & inputRange
            Selection.Columns.AutoFit 
        End With
    
    End Sub