工作中你可能会遇到这样一个问题。对相同颜色的单元格内容进行求和或者计数。本篇分享两种方法给大家,一种函数法,一种VBA法。
方法一:函数法
利用GET.CELL函数获取单元格格式内容,然后使用sumifs,countifs函数计算出需要的结果。这种方式需要增加辅助列,且需要先点击C2单元格后设置。(因为我要在C2显示结果)
GET.CELL为早期版本函数,目前使用的版本都较高,所以需要通过名称管理器自定义。
GET.CELL(Type_num,Reference)中Type_num 1-66代表不同的含义,63代表单元格的填充(背景)颜色。
方法二:VBA法
通过编辑自定义函数,可以不加辅助的快速计算出所需结果。
通过循环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 Integer
Dim rg As Range
Application.Volatile
For Each rg In countrange
If rg.Interior.ColorIndex = col.Interior.ColorIndex Then
Count颜色 = Count颜色 + 1
End If
Next
End Function
Function Sum颜色(sumrange As Range, col As Range) As Integer
Dim rg As Range
Application.Volatile
For Each rg In sumrange
If rg.Interior.ColorIndex = col.Interior.ColorIndex Then
Sum颜色 = Application.Sum(rg) + Sum颜色
End If
Next
End Function