excel学习库

excel表格_excel函数公式大全_execl从入门到精通

EXCELVBA按颜色求和与计数

有时候会遇到这样一个问题

有些单元格被标记了颜色

比如

单元格F3和F5

(注:这里是举例只取了两个)

(如果真是两个直接相加就好了^v^)

需要得到这些标记了颜色的单元格的和

或者

对这个颜色进行计数

针对这个问题

方法:查找 单元格颜色

可以用一下

但不是太好用

在这里呢

我们的解决方案还是要掏出VBA

区别在于

这是个自定义函数

求和 单元格F11输入公式

=SumByColor(F2:F6,D11)

计数 单元格F12输入公式

=CountByColor(F2:F6,D11)

使用与内置EXCEL函数一致

代码按ALT+F11打开VBE

复制粘贴到模块中就可以了

会用加载宏就丢加载宏里

代码如下:

'按单元格填充颜色求和

'Sum_range求和区域,Ref_color参考颜色所在单元格

Function SumByColor(Sum_range As Range, Ref_color As Range) As Double

Application.Volatile '易失性

Set Sum_range = Application.Intersect(ActiveSheet.UsedRange, Sum_range)

'相交,防止选择区域过大

Dim iCol As Long

Dim rCell As Range

SumByColor = 0 '初始化

iCol = Ref_color.Interior.ColorIndex 'rg.Font.Color 可改为字体

'引用单元格颜色索引

For Each rCell In Sum_range

If iCol = rCell.Interior.ColorIndex And WorksheetFunction.IsNumber(rCell) Then

'判断颜色是否相同 且为数字 文本不参与累计

SumByColor = SumByColor + rCell.Value

'累加

End If

Next rCell

End Function

'按单元格填充颜色计数

'Count_range计数区域,Ref_color参考颜色所在单元格

Function CountByColor(Count_range As Range, Ref_color As Range) As Long

Dim rg As Range '定义变量为单元格

For Each rg In Count_range '遍历计数区域的所有单元格

If rg.Interior.Color = Ref_color.Interior.Color Then '判断颜色是否相同

CountByColor = CountByColor + 1 '计数

End If

Next

End Function

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2024年12月    »
1
2345678
9101112131415
16171819202122
23242526272829
3031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
      友情链接