基于背景/字体颜色统计/求和单元格值及同字体颜色单元格计数咨询
嘿,这个需求我之前帮同事处理过,Excel里按颜色统计/求和确实得用点小技巧,分两种场景(VBA自定义函数和无VBA的365方法)给你说清楚:
一、通用方法:用VBA自定义函数(兼容所有Excel版本)
不管你用的是Excel 2016还是365,这个方法都能搞定,而且逻辑直观。
1. 统计相同字体颜色的单元格数量
步骤:
- 按
Alt + F11打开VBA编辑器 - 右键左侧的工作表/工作簿,选择「插入」→「模块」
- 粘贴下面的代码:
Function CountFontColor(rng As Range, colorCell As Range) As Long Dim cell As Range Dim targetColor As Long ' 获取目标单元格的字体颜色代码 targetColor = colorCell.Font.Color ' 遍历目标区域,统计颜色匹配的单元格 For Each cell In rng If cell.Font.Color = targetColor Then CountFontColor = CountFontColor + 1 End If Next cell End Function
- 回到Excel界面,在空白单元格输入公式:
=CountFontColor(要统计的区域, 目标颜色单元格)
比如要统计A1:C10里和D1字体颜色相同的单元格数,就写=CountFontColor(A1:C10,D1)
2. 统计相同背景颜色的单元格数量
和上面逻辑一致,只是把字体颜色换成背景颜色,代码如下:
Function CountFillColor(rng As Range, colorCell As Range) As Long Dim cell As Range Dim targetColor As Long targetColor = colorCell.Interior.Color For Each cell In rng If cell.Interior.Color = targetColor Then CountFillColor = CountFillColor + 1 End If Next cell End Function
用法:=CountFillColor(A1:C10,D1)
3. 按字体颜色求和单元格值
把统计逻辑改成累加单元格值即可:
Function SumFontColor(rng As Range, colorCell As Range) As Double Dim cell As Range Dim targetColor As Long targetColor = colorCell.Font.Color For Each cell In rng If cell.Font.Color = targetColor Then SumFontColor = SumFontColor + cell.Value End If Next cell End Function
用法:=SumFontColor(A1:C10,D1)
4. 按背景颜色求和单元格值
同理修改背景颜色的求和函数:
Function SumFillColor(rng As Range, colorCell As Range) As Double Dim cell As Range Dim targetColor As Long targetColor = colorCell.Interior.Color For Each cell In rng If cell.Interior.Color = targetColor Then SumFillColor = SumFillColor + cell.Value End If Next cell End Function
用法:=SumFillColor(A1:C10,D1)
⚠️ 注意:当你修改单元格颜色后,需要按 F9 手动触发公式重新计算(默认Excel不会把颜色变化视为计算触发条件)
二、无VBA方法:适合Excel 365/2021用户
如果你不想用VBA,可以借助GET.CELL宏表函数+普通统计函数实现:
统计/求和字体颜色
- 按
Ctrl + F3打开「名称管理器」,点击「新建」 - 名称设为
FontColorCode,引用位置输入:=GET.CELL(24,Sheet1!A1)(把Sheet1改成你的工作表名,A1是要获取颜色的第一个单元格) - 在目标区域旁边插入一列(比如B列),输入
=FontColorCode并下拉填充,这列会显示每个单元格的字体颜色代码 - 统计数量:用
COUNTIF,比如=COUNTIF(B1:B10,FontColorCode(D1)) - 求和:用
SUMIF,比如=SUMIF(B1:B10,FontColorCode(D1),A1:A10)
统计/求和背景颜色
和上面步骤一致,只是把GET.CELL的参数改成63:
- 新建名称
FillColorCode,引用位置:=GET.CELL(63,Sheet1!A1) - 填充颜色代码列后,用
COUNTIF或SUMIF统计即可
⚠️ 注意:这个方法的颜色代码列不会自动更新,修改颜色后需要按F9刷新。
内容的提问来源于stack exchange,提问作者Superstar




