搜档网
当前位置:搜档网 › 按指定的填充颜色计算单元格的个数及求和

按指定的填充颜色计算单元格的个数及求和

按指定的填充颜色计算单元格的个数及求和
按指定的填充颜色计算单元格的个数及求和

按指定的填充颜色计算单元格的个数及求和

这个要使用到自定义函数.

VBA编辑器中.新建一模块,加入代码如下:

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 ,可以统计区域中某种颜色的个数。这两个自定义函数都有两个参数,前一个参数指定包含某种颜色的单元格,后一个参数为求和或计数区域。

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

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

=sumByColor(A1,A1:B10)

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

=CountByColor(A1,A1:B10)

这个方法不适用条件格式

虽然不是很方便.但比使用宏表函数并加辅助列要好的多了.同理也可以计算有字体颜色的数字个数及求和.

代码以后再上

相关主题