返回条件格式单元格的内部颜色的函数



我想要一个函数,它返回条件格式单元格的颜色索引值。

它用于检查一行中的多个单元格,如果它们使用条件格式突出显示,则需要执行操作 - 检查单元格中是否有颜色比创建涵盖所有单元格条件的组合条件公式更简单。或者我是这么想的。

下面的代码返回一个 #VALUE 错误,尽管代码在味精框中工作。

Function fillcolour(rng as Range) as variant
    fillcolour=rng.Displayformat.Interior.ColorIndex
End Function

期望看到返回的颜色索引值,但得到 #VALUE

要使用更改事件:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    Call fillcolour(Cells(1, 1))
    Application.EnableEvents = True
End Sub

Function fillcolour(ring As Range) As Variant
    fillcolour = ring.DisplayFormat.Interior.Color
    Cells(1, 2) = fillcolour
End Function

每次更改单元格的内容时,它都会在单元格 B1 中显示背景颜色(即使它来自条件格式(。

但是,此事件返回一个目标,其中包含导致该事件的行和列(Target.Row、Target.Column等(。可以使用此目标直接检测在单元格上所做的更改。

当单元格在新计算期间发生更改时,不会发生此事件。使用 Calculate 事件检测范围/单元格中的更改。

请参阅此链接,了解您遇到此问题的原因。不能在用户定义的函数中使用该DisplayProperty。它在 VBA 环境中或从消息框调用时有效,但在从工作表调用时则不然。解决方法是从代码中删除.DisplayFormat,如下所示:

Function fillcolour(rng as Range) as variant
fillcolour=rng.Interior.ColorIndex
End Function

你试过吗?

Function fillcolour(ring as Range) as variant
fillcolour=rng.DisplayFormat.Interior.Color
End Function

将其分配给单元格的事件更改

感谢 Asger 在这里提供帮助。我现在有一个如下函数:

Function CFCheck(rng as range) as Integer
CFCheck = rng.FormatConditions.Count
End Function

因此,如果返回的值为>0,它可以触发操作

在进一步的测试中,意识到此功能只是区分具有CF的细胞和没有CF的细胞,这很有帮助,但在我遇到的情况下没有。我需要一些东西来查看具有 CF 但 CF 没有应用颜色,因为条件尚未满足。

最新更新