根据颜色求和与计数

一、代码展示
1.根据颜色求和代码
Function SumColor(i As Range, ary1 As Range) As Long
Dim icell As Range
Application.Volatile
For Each icell In ary1
If icell.Interior.ColorIndex = i.Interior.ColorIndex Then
SumColor = Application.Sum(icell) + SumColor
End If
Next icell
End Function
2.根据颜色计数代码
Function CountColor(x As Range, ary2 As Range)
Application.Volatile
For Each i In ary2
If i.Interior.ColorIndex = x.Interior.ColorIndex Then
CountColor = CountColor + 1
End If
Next
End Function
在这里我们定义了SumColor与CountColor两个自定义函数,
SumColor:对指定颜色的单元格求和
第一参数:想要求和的单元格颜色
第二参数:求和的数据区域
CountColor:对指定颜色的单元格计数
第一参数:想要计数的单元格颜色
第二参数:想要计数的单元格区域
二、设置自定义函数
我们先点击开发工具,然后点击visal basic,然后在vba的编辑界面中点击插入,选择模块,将刚才定义的两个函数粘贴进去,直接将界面关闭即可

三、使用函数
自定义函数与内置函数的使用方法是一摸一样的,我只需输入函数对应的名称,然后填写相应的参数即可

http://www.360doc.com/content/19/1122/14/58195209_874767769.shtml