excel实现按指定的单元格颜色进行计数或求和实例教程

如果Excel工作表的某区域中包含不同的底纹颜色,我们可以用一个自定义函数对该区域按指定的单元格颜色进行计数或求和。方法是:

1.按Alt+F11,打开VBA编辑器。

2.单击菜单“插入→模块”,将插入名称为“模块1”的模块,在右侧的代码窗口中输入下列代码:

Function SumByColor(Ref_color As Range, Sum_range As Range)
Application.Volatile
Dim iCol As Integer
Dim rCell As Range
iCol = Ref_color.Interior.ColorIndex
For Each rCell In Sum_range
If iCol = rCell.Interior.ColorIndex Then
SumByColor = SumByColor + rCell.Value
End If
Next rCell
End Function

Function CountByColor(Ref_color As Range, CountRange As Range)
Application.Volatile
Dim iCol As Integer
Dim rCell As Range
iCol = Ref_color.Interior.ColorIndex
For Each rCell In CountRange
If iCol = rCell.Interior.ColorIndex Then
CountByColor = CountByColor + 1
End If
Next rCell
End Function

上述两个自定义函数,一个是SumByColor,可以对区域按指定单元格的颜色求和。另一个是CountByColor,可以统计区域中某种颜色的个数。这两个自定义函数都有两个参数,前一个参数指定包含某种颜色的单元格,后一个参数为求和或计数区域。

3.关闭VBA编辑器。

使用方法:假如要求和或计数的区域在A1:B10区域中。

求出该区域中单元格底纹颜色为红色的所有单元格数值之和,在单元格中输入公式:

=sumByColor(A1,A1:B10)

求出该区域中单元格底纹颜色为红色的所有单元格的个数,在单元格中输入公式:

=CountByColor(A1,A1:B10)

office办公软件入门基础教程 » excel实现按指定的单元格颜色进行计数或求和实例教程

本文链接:【excel实现按指定的单元格颜色进行计数或求和实例教程】https://www.officeapi.cn/34604.html

OFFICE,天天学一点,进步多一点

联系我们