Function to return interior colour of conditional formatted cell

主宰稳场 提交于 2019-12-24 05:12:25

问题


I want a function that returns a value for the colour index of a conditionally formatted cell.

It is being used to check a number of cells in a row that if they highlighted using conditional formatting then an action will be required - it is simpler to check if there is a colour in the cell rather than create a combined conditional formula covering the conditions of all the cells. Or so I thought..

The code below is returning a #VALUE error although the code works in a msg box..

Function fillcolour(rng as Range) as variant

    fillcolour=rng.Displayformat.Interior.ColorIndex

End Function

Expect to see a value for the colour index returned but getting #VALUE


回答1:


To use the change event:

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

Each time you change the contents of a cell it will show you the background color in cell B1 (even if it comes from a conditional format).

However, this event returns a target with the row and column that caused the event (Target.Row, Target.Column, among many other things). You can use this target to detect the change you have made directly on the cell.

This event does not occur when the cells change during a new calculation. Use the Calculate event to detect a change in your range / cell.




回答2:


Please see this link on why you are having this issue. You can't use the DisplayProperty in user-defined functions. It works in the VBA environment or when called from a Message Box, but not when called from the Worksheet. The workaround is to remove .DisplayFormat from the code, as this:

Function fillcolour(rng as Range) as variant

fillcolour=rng.Interior.ColorIndex

End Function



回答3:


Have you tried?:

Function fillcolour(ring as Range) as variant

fillcolour=rng.DisplayFormat.Interior.Color

End Function

assign it to the event change of the cell




回答4:


Thank you to Asger to helping out here. I now have a function as follows:

Function CFCheck(rng as range) as Integer

CFCheck = rng.FormatConditions.Count

End Function

So it can then trigger an action if the value returned is >0

On further testing realised this function just differentiates between cells that have CF and those that don't which is helpful but not in the situation I have. I need something that looks at a cell that has CF but the CF hasn't applied colour because conditions haven't been met.



来源:https://stackoverflow.com/questions/56713741/function-to-return-interior-colour-of-conditional-formatted-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!