2016-08-03 214 views
3

有沒有人跑過一個實際上可以使用條件格式的函數?自定義excel公式函數UDF來計算條件格式

有一些插件的kutools和albebits但它們不是基於公式(你必須選擇手動一切)

我發現這一點,但只有手動格式

Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean) 
Dim rCell As Range 
Dim lCol As Long 
Dim vResult 
lCol = rColor.Interior.ColorIndex 
If SUM = True Then 
    For Each rCell In rRange 
    If rCell.Interior.ColorIndex = lCol Then 
      vResult = WorksheetFunction.SUM(rCell) + vResult 
    End If 
    Next rCell 
Else 
    For Each rCell In rRange 
    If rCell.Interior.ColorIndex = lCol Then 
      vResult = 1 + vResult 
    End If 
    Next rCell 
End If 
ColorFunction = vResult 
End Function 

回答

3

繼工作從@Jeeped和@Comintern ...

這對我的作品 - 一個簡單的例子:

Function WrapCountReds(rRange) 
    WrapCountReds = rRange.Parent.Evaluate("CountReds(" & _ 
          rRange.Address(False, False) & ")") 
End Function 

'can't call this directly from a worksheet but can be called via evaluate 
Public Function CountReds(rRange As Range) 

    Dim rCell As Range 
    Dim vResult 

    For Each rCell In rRange 
     If rCell.DisplayFormat.Interior.ColorIndex = 3 Then 
      vResult = 1 + vResult 
     End If 
    Next rCell 

    CountReds = vResult 
End Function 

工作表使用示例:

=WrapCountReds("A1:A100") 
+1

有趣。我從來沒有想過使用Evaluate作爲包裝函數。 – Comintern

+1

@Comintern - related:https://stackoverflow.com/questions/23433096/using-a-udf-in-excel-to-update-the-worksheet/23437280#23437280 –