2

I'm trying to display the colour from the conditional formatting in excel. In excel I simply use =CheckColour(B5) for example, and when I hit return it works. However, when I ask the sheet to calculate, the function gives #VALUE! and I don't know where I've gone wrong. Any help is appreciated as I'm a beginner at VBA. Thanks

    Function CheckColour(range)
        If range.DisplayFormat.Interior.Color = RGB(255, 0, 0) Then
        CheckColour = "Red"
        ElseIf range.DisplayFormat.Interior.Color = RGB(0, 130, 59) Then
        CheckColour = "Green"
        Else
        CheckColour = "Amber"
        End If
    End Function
2
  • Unrelated, but your signature would be much more explicit if it were Public Function CheckColour(ByVal target As Range) As String - right now it's implicitly public, range is implicitly ByRef and Variant, and the function implicitly returns a Variant. Commented Feb 7, 2017 at 16:10
  • Thank you for your help Mat Commented Feb 7, 2017 at 16:19

2 Answers 2

6

Yep, because:

Note that the DisplayFormat property does not work in user defined functions. For example, in a worksheet function that returns the interior color of a cell, you use a line similar to: Range(n).DisplayFormat.Interior.ColorIndex. When the worksheet function executes, it returns a #VALUE! error. Ref.

Instead use:

range.Interior.Color 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Alex, so is there any way I can take the conditional formatting colour and display it as a word, say red, green etc. ?
0

This (simplified example) seems to work for me:

Public Function CheckColour(src As Range)
    Application.Volatile
    CheckColour = src.Parent.Evaluate("GetColor(" & src.Address(False, False) & ")")
End Function

Public Function GetColor(src As Range)
    GetColor = src.DisplayFormat.Interior.Color
End Function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.