经常跟表格打交道的朋友是不是遇到这种情况:根据单元格的颜色或者字体的颜色对单元格的数字进行求和。系统自带的求和函数SUM根本无法满足要求。今天给大家分享一个VBA自定义颜色求和函数SumColour,无需复杂操作,一键实现【按底色求和、按字体颜色求和、底色+字体双重匹配求和】三种场景,完美适配所有颜色统计需求。一、函数核心功能
这款SumColour自定义函数,是专门为Excel颜色统计打造的万能公式,彻底弥补Excel原生函数的短板,支持三种求和模式,全覆盖办公场景:
模式0(默认):仅匹配单元格底纹颜色求和(最常用,适配标色备注、分类统计场景)
模式1:仅匹配单元格字体颜色求和(适配红色标注重点数据、异色字体统计场景)
模式2:同时匹配【底纹+字体颜色】双重条件求和(精准筛选,避免同底色不同字体数据干扰)
二、函数语法与参数说明
SumColour (求和区域,参考单元格,[模式0底1字2双])
| | |
| | |
| | |
| 可选参数,不填默认0(底纹求和),1=字体求和,2=双重匹配求和 | |
Function SumColour(求和区域 As Range, 参考单元格 As Range, Optional 模式0底1字2双 As Integer = 0) As Double ' 区域: 需要求和的数据区域 ' 参考单元格: 包含目标颜色的参考单元格 ' 模式: 0=按底纹颜色(默认), 1=按字体颜色, 2=同时匹配底纹和字体 Dim cell As Range Dim total As Double Dim targetInteriorColor As Long Dim targetFontColor As Long targetInteriorColor = 参考单元格.Interior.Color targetFontColor = 参考单元格.Font.Color total = 0 For Each cell In 求和区域 If IsNumeric(cell.value) And Not IsError(cell.value) Then Select Case 模式0底1字2双 Case 0 If cell.Interior.Color = targetInteriorColor Then total = total + cell.value End If Case 1 If cell.Font.Color = targetFontColor Then total = total + cell.value End If Case 2 If cell.Interior.Color = targetInteriorColor And cell.Font.Color = targetFontColor Then total = total + cell.value End If End Select End If Next cell SumColour = totalEnd Function
五、使用方法
- 打开 Excel,按
Alt+F11 打开 VBA 编辑器;