You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求支持区域自动扩展的Excel按文本颜色求和公式

按指定文本颜色动态求和解决方案

方案1:无VBA方案(依赖宏表函数)

适合不愿启用VBA的场景,步骤如下:

  1. 定义名称获取字体颜色
    打开「公式」→「名称管理器」→ 新建名称:
    • 名称:FontColorCode
    • 引用位置:=GET.CELL(24,INDIRECT("rc",FALSE))
      该公式返回当前单元格字体颜色的十进制RGB值,需启用宏生效。
  2. 转换为超级表实现自动扩展
    选中数据区域(B1:H216)按Ctrl+T,勾选「我的表格有标题」,自动命名为Table1(可自定义名称)。后续新增数据时,表格会自动扩展计算区域。
  3. 编写求和公式
    在J3(对应绿色#34a853)输入:
    =SUM(IF(FontColorCode=HEX2DEC("34a853"),Table1[#All],""))
    
    新版Excel直接回车,旧版需按Ctrl+Shift+Enter触发数组计算。
    其他颜色对应公式:
    • J4(橙色#ff6d01):=SUM(IF(FontColorCode=HEX2DEC("ff6d01"),Table1[#All],""))
    • J5(蓝色#4285f4):=SUM(IF(FontColorCode=HEX2DEC("4285f4"),Table1[#All],""))
    • J6(红色#ea4335):=SUM(IF(FontColorCode=HEX2DEC("ea4335"),Table1[#All],""))

方案2:VBA自定义函数(更稳定)

若宏表函数存在兼容性问题,自定义函数是更可靠的选择:

  1. 按Alt+F11打开VBA编辑器,右键左侧工程窗口→插入→模块,粘贴以下代码:
    Function SumByFontColor(rng As Range, targetColor As String) As Double
        Dim cell As Range
        Dim targetRGB As Long
        ' 将十六进制颜色转为RGB长整型
        targetRGB = RGB("&H" & Right(targetColor, 2), "&H" & Mid(targetColor, 3, 2), "&H" & Left(targetColor, 2))
        
        For Each cell In rng
            If cell.Row <> 1 Then ' 跳过首行标题行
                If cell.Font.Color = targetRGB Then SumByFontColor = SumByFontColor + cell.Value
            End If
        Next cell
    End Function
    
  2. 同样将数据区域转为超级表后,在J3输入:
    =SumByFontColor(Table1[#Data],"34a853")
    
    其他单元格对应修改颜色代码即可:
    • J4:=SumByFontColor(Table1[#Data],"ff6d01")
    • J5:=SumByFontColor(Table1[#Data],"4285f4")
    • J6:=SumByFontColor(Table1[#Data],"ea4335")

关键说明

  • 超级表是实现区域自动扩展的核心,新增数据直接在表格下方输入即可,无需修改公式;
  • 两种方案均需将文件保存为.xlsm格式(启用宏的工作簿),首次打开时需允许宏运行。

内容的提问来源于stack exchange,提问作者KCP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 22:00:21