Search code examples
if-statementgoogle-sheetssumgoogle-sheets-formulaarray-formulas

Is there a way to count from last condition x?


I have a complex set of data that can return 3 different conditions per row. I need to be able to count the last x rows matching one of the specific conditions.

The following formula has been working well for me, but I have discovered a glitch in one instance of this formula (the formula is replicated at least a dozen times)

=ArrayFormula(LOOKUP(9.99999999999999E+307,IF(FREQUENCY(IF(AQ:AQ)=1,ROW(AQ:AQ)),IF(AQ:AQ<>1,ROW(AQ:AQ)))=0,FREQUENCY(IF(AQ:AQ=1,ROW(AQ:AQ)),IF(AQ:AQ=0,ROW(AQ:AQ))))))

Current criteria are as such:
0: Condition x met - Reset counter
1: Condition y met - Increment counter
2: Condition z met - Ignore this row

Therefore this:
1
2
2
2
1
1
0
1
1
1

Should output: 3

This:
1
2
0
2
2
1
2
1

Should output: 2

However the glitch I have encountered isn't resetting the counter when 0 is reached, for example:
1
2
1
2
1
1
2
2
2
2
0

Should output: 0

But in fact is outputting: 4

I have tested all possible conditions with that specific data set and I cannot rectify the issue. I believe there is an error in the formula (specifically the 9.99999999999999E+307) but I wrote it so long ago that I cannot successfully debug it. I have tried 1E+306 but the result is the same.


EDIT1: Upon request I have included as stripped down version of the sheet as I can while recreating the issue.

https://docs.google.com/spreadsheets/d/1SOXiFMEQelqptBvjcabMZGNgG60TRRbe_b65rzT1bi0/edit?usp=sharing

If you scroll to the bottom of the sheet you can see Col AQ has a 0, as a result the value in the cell AF2 should be 0.

You will notice in the sheet that I am using Named Ranges.


EDIT2: player0's answer was PERFECT!! <3

I modified the new formula to adapt to my spreadsheet so it could accommodate Named Ranges and drop-down lists. This question helped me a lot with that:

Convert column index into corresponding column letter

The final formula (just FYI) turned out to be:

=ARRAYFORMULA(COUNTIF( INDIRECT(REGEXEXTRACT(ADDRESS(ROW(), column(INDIRECT($A$1 & Z$1 & "L"))), "[A-Z]+")& MAX(IF((INDIRECT($A$1 & Z$1 & "L")=0)*(INDIRECT($A$1 & Z$1 & "L")<>""), ROW(INDIRECT($A$1 & Z$1 & "L"))+1,5))&":"& REGEXEXTRACT(ADDRESS(ROW(), column(INDIRECT($A$1 & Z$1 & "L"))), "[A-Z]+")), 1))


Solution

  • =ARRAYFORMULA(COUNTIF(INDIRECT("A"&
     MAX(IF((A2:A=0)*(A2:A<>""), ROW(A2:A)+1, ROW(A2)))&":A"), 1))
    

    0


    spreadsheet demo