Excel按颜色求和、计数,学会方法很简单
在Excel数据处理中,有时需要根据单元格的背景颜色或字体颜色进行求和与计数操作,例如统计特定颜色标记的夜班产量。由于Excel未内置直接按颜色处理数据的函数,通常需要通过VBA自定义函数或安装第三方插件来实现这一需求。
01VBA自定义函数实现
通过编写VBA代码,可以创建四个自定义函数,分别解决背景颜色计数、背景颜色求和、字体颜色计数以及字体颜色求和的问题。具体代码如下:
- CountByBGColor(根据背景颜色计数)
Function CountByBGColor(Col As Range, CountRange As Range)
Application.Volatile
Dim iCell As Range
CountByBGColor = 0
For Each iCell In CountRange
If iCell.Interior.Color = Col.Interior.Color Then
CountByBGColor = CountByBGColor + 1
End If
Next
End Function - SumByBGColor(根据背景颜色求和)
Function SumByBGColor(Col As Range, SumRange As Range)
Application.Volatile
Dim iCell As Range
SumByBGColor = 0
For Each iCell In SumRange
If iCell.Interior.Color = Col.Interior.Color Then
SumByBGColor = SumByBGColor + Application.WorksheetFunction.Sum(iCell)
End If
Next
End Function - CountByFontColor(根据字体颜色计数)
Function CountByFontColor(Col As Range, CountRange As Range)
Application.Volatile
Dim iCell As Range
CountByFontColor = 0
For Each iCell In CountRange
If iCell.Font.Color = Col.Font.Color Then
CountByFontColor = CountByFontColor + 1
End If
Next
End Function - SumByFontColor(根据字体颜色求和)
Function SumByFontColor(Col As Range, SumRange As Range)
Application.Volatile
Dim iCell As Range
SumByFontColor = 0
For Each iCell In SumRange
If iCell.Font.Color = Col.Font.Color Then
SumByFontColor = SumByFontColor + Application.WorksheetFunction.Sum(iCell)
End If
Next
End Function
上述函数的用法统一:第一个参数为提供颜色样本的单元格(Col),第二个参数为需要进行统计的目标区域(Range)。例如,使用公式“=CountByBGColor(H$1,B3:F3)”即可统计B3:F3区域内与H1单元格背景色相同的单元格数量。代码录入完成后,需将文件保存为.xlsm格式以保留宏功能。
02函数的永久调用设置
- 按F12键打开“另存为”对话框,将保存类型选择为“Excel加载项(*.xlam)”,存放位置保持默认。
- 在Excel【开发工具】选项卡下点击【Excel加载项】按钮,浏览并勾选刚才保存的加载项文件。
- 设置完成后,在任意Excel文件中输入“=color”即可调出上述自定义函数进行使用。
03插件替代方案
如果不熟悉VBA代码编写,可以使用第三方Office增强插件(如易用宝)来实现相同功能。在插件选项卡中选择【公式模板】,找到“按颜色计数”类别,输入相应参数即可快速完成求和与计数操作。
当前文章无评论,是时候发表评论了