VBA macro tip contributed by
Erlandsen
Data Consulting offering Microsoft Excel Application development,
template customization, support and training solutions
With the built-in COUNTA()-function it's not possible to count cells in a range depending on each cells background color.
With the custom function below you can count the cells depending on their background color:
Function CountByColor(InputRange As Range, ColorRange as Range) As Long
Dim cl As Range, TempCount As Long, ColorIndex As Integer
ColorIndex = ColorRange.Cells(1, 1).Interior.ColorIndex
TempCount = 0
For Each cl In InputRange.Cells
If cl.Interior.ColorIndex = ColorIndex Then
TempCount = TempCount + 1
End If
Next cl
Set cl = Nothing
CountByColor = TempCount
End Function
This function is used in the same way as built-in worksheetfunctions. InputRange is the range that the function
is going to count, ColorRange is a reference to a cell containing the background color you wish to count.
In Excel 5/95 the variables InputRange and ColorRange must be declared as Variant instead of Range.
This function can easily be adapted for use with other worksheetfunctions that you wish to use on cells
with different background colors.
good one.. but not refreshing
sathish wrote on December 31, 1969 19:00 EST
good one..
but is not automatically refreshed when the cell color is changed
wrote on December 31, 1969 19:00 EST
Be aware that the changing of a cells fill color will not cause the function to recalculate, even if you press F9. You will need to either select the cell and re-enter the formula, or go to Edit>Replace and replace = with =, or use Ctrl+Alt+F9
Terms
and Conditions of use
The applications/code on this site are distributed as is and without warranties
or liability. In no event shall the owner of the copyrights, or the authors
of the applications/code be liable for any loss of profit, any problems
or any damage resulting from the use or evaluation of the applications/code.