如果Excel工作表的某区域中包含不同的底纹颜色,我们可以用一个自定义函数对该区域按指定的单元格颜色进行计数或求和。方法是:
1.按Alt+F11,打开VBA编辑器。
2.单击菜单“插入→模块”,将插入名称为“模块1”的模块,在右侧的代码窗口中输入下列代码:
Function SumByColor(Ref_color As Range, Sum_range As Range)
Application.Volatile
Dim iCol As Integer
Dim rCell As Range
iCol = Ref_color.Interior.ColorIndex
For Each rCell In Sum_range
If iCol = rCell.Interior.ColorIndex Then
SumByColor = SumByColor + rCell.Value
End If
Next rCell
End Function
Function CountByColor(Ref_color As Range, CountRange As Range)
Application.Volatile
Dim iCol As Integer
Dim rCell As Range
iCol = Ref_color.Interior.ColorIndex
For Each rCell In CountRange
If iCol = rCell.Interior.ColorIndex Then
CountByColor = CountByColor + 1
End If
Next rCell
End Function
按字求颜色
在Excel的内建功能, 内建函数中, 应没有针对颜色而自动计算的方法。
故可能是唯一办法- VBA自定义函数
我刚写了一个简单的VBA,绝对可以做到你的要求
Function COLORSUM(xx As Range, yy As Range) As Double
y = yy.Font.ColorIndex
For Each x In xx
If x.Font.ColorIndex = y Then
xxx = xxx + x.Value
End If
Next
COLORSUM = xxx
End Function
假设你的数字是在A1:A100
而A2的数字颜色是作为自动求和的识别
只要将上述VBA贴在模块上, COLORSUM函数便可以使用
输入公式=COLORSUM(A1:A100,A2)
便会所有与A2相同颜色的数字, 自动求和
联系客服