views:

139

answers:

1

I have a moderately sized dataset in Excel from which I wish to extract the maximum value of the values in Column B, but those that correspond only to cells in Column A that satisfy certain criteria. The desired functionality is similar to that of SUMIF or COUNTIF, but neither of those return data that is necessary. There isn't a MAXIF function, so I ask the SO community: how do I emulate one?

+1  A: 

You can use an array formula.In the cell in which you want the max calculated enter: =Max(If([test],[if true],[if false]) where you replace the values in square brackets with the test, what to return if true and what to return if false. For example:

=MAX(IF(MOD(A2:A25,2)=0,A2:A25,0)

In this formula I return the value in column A if the value divided by 2 has no remainder. Notice that I use a range of cells in my comparison and in the value if false rather than a single cell.

Now, while still editing the cell, hit Ctrl+Shift+Enter (hold down the Ctrl key and the Shift together and then hit enter).

This creates an array formula that acts on each value in the range.

EDIT BTW, did you want to do this programmatically or manually? If programmatically, then what environment are you using? VBA? C#?

EDIT If via VBA, you need to use the FormulaArray property and R1C1 references like so:

Range("A1").Select
Selection.FormulaArray = "=MAX(IF(MOD(R[1]C:R[24]C,2)=0,R[1]C:R[24]C,0))"
Thomas