2

I have this function to get the color which is set by a conditional format.

Function ColorIndex(CellColor As Range)
ColorIndex = CellColor.DisplayFormat.Interior.ColorIndex
End Function

But when I use this function in my worksheet it always returns as #value.

How can I make this work?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • That is exactly the behaviour described in the documentation: [Range.DisplayFormat property](https://learn.microsoft.com/en-us/office/vba/api/excel.range.displayformat). It says also ***"Note that the DisplayFormat property does not work in user defined functions."*** but you actually tried to use it in a user defined function. So it is a feature not a bug. – Pᴇʜ Mar 15 '19 at 08:43

2 Answers2

2

Try this

Dim clrIndex As Integer

Function ColorIndex(CellColor As Range)
    CellColor.Parent.Evaluate "GetColor(" & CellColor.Address(False, False) & ")"
    ColorIndex = clrIndex
End Function

'~~> Get the color index of the cell and store in a temp variable
Sub GetColor(RefCell As Range)
    clrIndex = RefCell.DisplayFormat.Interior.ColorIndex
End Sub

enter image description here

For more explanation you may want to see this amazing Thread by @TimWilliams

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
0

The solution is this:

Dim clrIndex As Integer

Function ColorIndex(CellColor As Range)
CellColor.Parent.Evaluate "GetColor(" & CellColor.Address(False, False) & ")"
ColorIndex = clrIndex
End Function

'~~> Get the color index of the cell and store in a temp variable
Sub GetColor(RefCell As Range)
clrIndex = RefCell.DisplayFormat.Interior.ColorIndex
End Sub

And for updating the code i use

Application.CalculateFullRebuild

Thanks @Siddharth Rout