参考网络代码,自己写了二个通用的自定义函数,用于统计不同颜色的单元格数值或个数。
1、SumColor函数
统计选择范围内不同颜色的单元格数值
2、CountColor函数
统计选择范围内不同颜色的单元格个数
1 Function SumColor(rng As Range, cellColor As Range, N As Byte) As Double
2 '输入=SumColor(A1:A10, A1, 0),其中A1:A10是统计的范围,A1是统计的颜色所在的单元格,0表示按照背景颜色统计,1表示按字体颜色统计
3 Dim cell As Range
4 Dim Sum As Double
5 Application.Volatile True '单元格发生重新计算,那么函数会重新计算,更新它的结果
6 Sum = 0
7 If N = 0 Then
8 For Each cell In rng
9 If cell.Interior.ColorIndex = cellColor.Interior.ColorIndex Then
10 Sum = Application.Sum(cell) + Sum
11 End If
12 Next cell
13 ElseIf N = 1 Then
14 For Each cell In rng
15 If cell.Font.ColorIndex = cellColor.Font.ColorIndex Then
16 Sum = Application.Sum(cell) + Sum
17 End If
18 Next cell
19 Else
20 Exit Function
21 End If
22 SumColor = Sum
23 End Function
1 Function CountColor(rng As Range, cellColor As Range, N As Byte) As Long
2 '输入=SumColor(A1:A10, A1, 0),其中A1:A10是统计的范围,A1是统计的颜色所在的单元格,0表示按照背景颜色统计,1表示按字体颜色统计
3 Dim cell As Range
4 Dim Sum As Long
5 Application.Volatile True '单元格发生重新计算,那么函数会重新计算,更新它的结果
6 Count = 0
7 If N = 0 Then
8 For Each cell In rng
9 If cell.Interior.ColorIndex = cellColor.Interior.ColorIndex Then
10 Count = Count + 1
11 End If
12 Next cell
13 ElseIf N = 1 Then
14 For Each cell In rng
15 If cell.Font.ColorIndex = cellColor.Font.ColorIndex Then
16 Count = Count + 1
17 End If
18 Next cell
19 Else
20 Exit Function
21 End If
22 CountColor = Count
23 End Function