2015-04-02 67 views
-1

我有一些VB,允许我基于细胞颜色COUNTIF;COUNTIF细胞颜色是XXX&条件格式

Function COUNTIFCOLOR(rSample As Range, rArea As Range) As Long 
Dim rAreaCell As Range 
Dim lMatchColor As Long 
Dim lCounter As Long 

lMatchColor = rSample.Interior.Color 
For Each rAreaCell In rArea 
    If rAreaCell.Interior.Color = lMatchColor Then 
     lCounter = lCounter + 1 
    End If 
Next rAreaCell 
CountColorIf = lCounter 
End Function 

要使用这一点,你就简单的说

=COUNTIFCOLOR(A5,J2:J15) 

随着A5作为参考这个颜色太一电池,和J2:J15被指望的范围内。

这有效,但是如果单元格已通过条件格式进行格式化,则它不包括返回的计数中的该单元格。

现在我被困=/

+0

UDF参考[这里](http://www.excelfox.com/forum/f22/get-displayed-cell-color-whether-from-conditional-formatting-or-not-338/)可能是利益。 – pnuts 2015-04-02 11:44:27

回答

0

有一个属性,它可以读取的条件格式的颜色。 不幸的是它不能在UDF中使用,但只能在subs中使用。 解决方法: 创建一个监听包含以下命令的工作表更改的事件过程: Target.interior.color = Target.DisplayFormat.interior.color。这会将条件内部颜色复制到内部颜色。

将命令Application.volatile添加到现有函数的开头,以在表单重新计算时执行。

这里是必需的事件过程:为你的函数的彩色复印后才能在未来的计算周期的影响

Private Sub Worksheet_Change(ByVal Target As Range) 
    Target.Interior.Color = Target.DisplayFormat.Interior.Color 
    Application.Calculate 
End Sub 

Applicaiton.calculate是必需的。 您可能希望将有效的目标范围限制为所需的区域以节省资源。

+0

非常感谢 – 2015-04-08 15:40:51