View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.worksheet.functions
Harlan Grove
 
Posts: n/a
Default How to sum data based on font or cell color?

Max wrote...
....
For CF cases, one way is to try using the same conditions as applied for the CF
Eg if col B is conditionally formatted with the formula: =A110,
then we could use something like this in say, C1: =SUMIF(A:A,"10",B:B)
to sum col B if col A 10

....

But if the conditional formatting formulas or conditions are unknown,
it's still possible to sum by color index using VBA. The following sums
by cell background color index, aka, interior color index.


Function foo(rng As Range, ci As Variant) As Double
Dim fc As FormatCondition, c As Range
Dim fcf1 As Variant, cv As Variant

For Each c In rng
cv = c.Value2

If VarType(cv) = vbDouble Then

If c.Interior.ColorIndex = ci Then
foo = foo + cv

Else
For Each fc In c.FormatConditions
fcf1 = Application.ConvertFormula( _
Application.ConvertFormula( _
fc.Formula1, xlA1, xlR1C1, , ActiveCell), _
xlR1C1, xlA1, xlAbsolute, c)

If Left(fcf1, 1) < "=" Then fcf1 = CDbl(fcf1)

If fc.Type = xlExpression Then

If CBool(Evaluate(fcf1)) Then
If fc.Interior.ColorIndex = ci Then foo = foo + cv
Exit For
End If

ElseIf (fc.Operator = xlEqual And cv = fcf1) _
Or (fc.Operator = xlNotEqual And cv < fcf1) _
Or (fc.Operator = xlLess And cv < fcf1) _
Or (fc.Operator = xlLessEqual And cv <= fcf1) _
Or (fc.Operator = xlGreater And cv fcf1) _
Or (fc.Operator = xlGreaterEqual And cv = fcf1) _
Or (fc.Operator = xlBetween And fcf1 <= cv _
And cv <= CDbl(fc.Formula2)) _
Or (fc.Operator = xlNotBetween And (cv < fcf1 _
Or CDbl(fc.Formula2) < cv)) Then
If fc.Interior.ColorIndex = ci Then foo = foo + cv
Exit For

End If

Next fc

End If

End If

Next c

End Function