在Excel文件中,有时需要在不同的情况下用不同的颜色标记单元格且录入相应的数据。可更加方便直观地看到该数据的情况
如迟到的标记为红色,早退标记为蓝色。迟到的时间不同,所扣的款也不同。
那么我们如何统计单元格的颜色个数和汇总相同单元格颜色的值
如下图所示
详细vba代码:
'统计相同单元格的个数 Function CountColor(col As Range, countrange As Range) As Integer Dim icell As Range Application.Volatile For Each icell In countrange If icell.Interior.ColorIndex = col.Interior.ColorIndex Then CountColor = CountColor + 1 End If Next icell End Function '统计相同颜色单元格的合计值 Function SumColor(col As Range, sumrange As Range) As Integer Dim icell As Range Application.Volatile For Each icell In sumrange If icell.Interior.ColorIndex = col.Interior.ColorIndex Then SumColor = Application.Sum(icell) + SumColor End If Next icell End Function
其中:col参数为:指定颜色的单元格,countrange和sumrange 参数为:统计区域
设计方法:
1.vbe窗口,插入模块-键入代码
2.在窗口调用代码,如单元格=CountColor(K1,H1:H10)