【VBA应用】(Excel 2003) 自定函数:按颜色加总,及计数
excel吧
全部回复
仅看楼主
level 10
siaojuen 楼主
Excel 2003 没有公式可以按颜色加总,计数。
以下是vba自定函数,可以求加总,计数,平均数。
将以下vba载入 "模块" ,跟著关掉vba编辑窗口。
Private Function bycol(target As Range, sample As Range, xtype As String)
Dim cell As Range, xsum, xcnt
For Each cell In target
If cell.Interior.ColorIndex <> sample(1).Interior.ColorIndex Then GoTo 888
If IsEmpty(cell) Then GoTo 888
If VarType(cell) <> 5 Then GoTo 888
xsum = xsum + cell.Value
xcnt = xcnt + 1
888:
Next
If xtype Like "[Ss]" Then
bycol = xsum
ElseIf xtype Like "[Cc]" Then
bycol = xcnt
ElseIf xtype Like "[Aa]" Then
bycol = Application.Evaluate("=" & xsum & "/" & xcnt)
Else
bycol = "#错误"
End If
End Function
公式原型:
 =bycol(统计区域,样板格,类形)
此例:
加总
=bycol(A1:D6,B5,"s")
计数
=bycol(A1:D6,B5,"c")
平均
=bycol(A1:D6,B5,"a")
2012年03月08日 14点03分 1
level 10
siaojuen 楼主
1楼是按单元格背境颜色计算。
下面是按字的颜色计算
Private Function byfontcol(target As Range, sample As Range, xtype As String)
Dim cell As Range, xsum, xcnt
For Each cell In target
If cell.Font.ColorIndex <> sample(1).Font.ColorIndex Then GoTo 888
If IsEmpty(cell) Then GoTo 888
If VarType(cell) <> 5 Then GoTo 888
xsum = xsum + cell.Value
xcnt = xcnt + 1
888:
Next
If xtype Like "[Ss]" Then
byfontcol = xsum
ElseIf xtype Like "[Cc]" Then
byfontcol = xcnt
ElseIf xtype Like "[Aa]" Then
byfontcol = Application.Evaluate("=" & xsum & "/" & xcnt)
Else
byfontcol = "#错误"
End If
End Function
公式:
加总
=byfontcol(A1:D6,A2,"s")
计数
=byfontcol(A1:D6,A2,"c")
平均
=byfontcol(A1:D6,A2,"a")
2012年03月08日 14点03分 2
level 10
siaojuen 楼主
【须知】
如果单元格的颜色是由条件化格式所变,以上自定函数无效。
2012年03月23日 00点03分 3
level 1
楼主问题是那些英文是什么,模块是什么,怎么操作,求详解。。。。真的很需要,就是第一个按背景查找的那个谢谢
2013年04月24日 18点04分 5
2014年06月18日 18点06分
level 1
一直报公式错误。
2014年12月10日 10点12分 6
level 1
大神你还在看帖没?需要您的帮助。
2015年07月23日 08点07分 7
level 5
大神你能解决我刚发的那个问题吗?(怎么统计一组单元格中数值为31且3为红色的单元格个数)
2017年03月19日 09点03分 8
level 7
excel下面代码写到了101行,怎么继续往下添加更多行,能看到的公式是下图这样,好像是代码写出来,求解,谢谢🙏
2018年05月03日 11点05分 9
1