Excel按单元格颜色进行求和或计数

工作中你可能会遇到这样一个问题 。


对相同颜色的单元格内容进行求和或者计数 。


本篇分享两种方法给大家,一种函数法,一种VBA法 。


第一种:函数法


利用GET.CELL函数获取单元格格式内容 , 然后使用sumifs,countifs函数计算出需要的结果 。这种方式需要增加辅助列,且需要先点击C2单元格后设置 。(因为我要在C2显示结果)


Excel按单元格颜色进行求和或计数



Excel按单元格颜色进行求和或计数



GET.CELL为早期版本函数,目前使用的版本都较高,所以需要通过名称管理器自定义 。


GET.CELL(Type_num,Reference)中Type_num 1-66代表不同的含义,63代表单元格的填充(背景)颜色 。


第二种:VBA法


通过编辑自定义函数,可以不加辅助的快速计算出所需结果 。


Excel按单元格颜色进行求和或计数



【Excel按单元格颜色进行求和或计数】通过循环For Each rg In countrange,不断判断单元格颜色是否与当前颜色一致来加以求和或者计数 。


需要注意,自定义函数只能放置在模块内才可以有效 。


Function Count颜色(countrange As Range, col As Range)其中countrangeAs Range为需计算区域,col As Range为目标颜色单元格 。


具体代码如下:
Function Count颜色(countrange As Range, col As Range) As IntegerDim rg As RangeApplication.VolatileFor Each rg In countrangeIf rg.Interior.ColorIndex = col.Interior.ColorIndex ThenCount颜色 = Count颜色1End IfNextEnd Function


Function Sum颜色(sumrange As Range, col As Range) As IntegerDim rg As RangeApplication.VolatileFor Each rg In sumrangeIf rg.Interior.ColorIndex = col.Interior.ColorIndex ThenSum颜色 = Application.Sum(rg)Sum颜色End IfNextEnd Function


欢迎点击关注,后续会有更多精彩内容!

相关经验推荐