阁主在工作中,偶尔会碰到需要对标记颜色后的数据进行求和的情况,但是EXCEL中又没有合适的函数可以用来进行按颜色求和,于是,阁主用VBA写了一个函数,以后用起来就方便了。
使用方法:
1、打开VBA编辑器。开发工具→Visual Basic。开发工具栏默认不显示,在选项中设置其可见。
2、插入模块。打开Visual Basic编辑器后,插入→模块,双击新插入的模块打开代码编辑窗口。
3、粘贴代码。复制下方代码粘贴到代码编辑窗口
4、在单元格中调用函数。函数有两个参数,第一个是需要求和的区域,第二个参数为求和所参照的颜色标准。
=SUMCOLOR(A1:D10,A1)
Public Function SUMCOLOR(CEL As Range, CEL2 As Range) Dim s As Range For Each s In CEL If s.Interior.Color = CEL2.Interior.Color Then SUMCOLOR = SUMCOLOR + s.Value End If Next End Function Public Function CELLCOLOR(CEL As Range) Dim colorArray() ReDim colorArray(CEL.Rows.Count - 1, CEL.Columns.Count - 1) For i = 0 To UBound(colorArray) For j = 0 To UBound(colorArray, 2) colorArray(i, j) = CEL.Cells(i + 1, j + 1).Interior.Color Next Next CELLCOLOR = colorArray End Function