2015-04-02 62 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