deasa
deasa

Reputation: 606

Cell's .Interior.ColorIndex Value Different From What Is Visible

SO Community,

The problem is that I have a cell that is colored red via conditional formatting, but when I check the cell's .Interior.ColorIndex, it returns 35, which corresponds to light green.

Contextual Information

  1. The cell in question is a merged cell, named partNumber_1, and it spans cells I12:L12
  2. In the immediate window, ?Range("I12").Interior.ColorIndex returns 35
  3. ?Range("partNumber_1").Interior.ColorIndex returns 35
  4. If I change 2. and 3. to .Interior.Color (to get the long value), it returns 13434828 which corresponds to RGB(205, 255, 205)
  5. The named range in question, partNumber_1 belongs to another named range, ScannedPartNumbers, which is the named range referenced in the conditional formatting formula.
  6. ?Range("ScannedPartNumbers").Interior.ColorIndex also returns 35

I apply and remove the conditional formatting via VBA, where target is the ScannedPartNumbers range, fillColor is 3 (red), and fontColor is 6 (yellow).

Public Sub AddBlankCellFormatCondition(target As range, fillColor As Integer, Optional fontColor As Integer = 1)
    target.Parent.Unprotect password:=Strings.Mypw
    With target
        .FormatConditions.Add Type:=xlBlanksCondition
        .FormatConditions(.FormatConditions.Count).SetFirstPriority
        With .FormatConditions(1)
            .Interior.ColorIndex = fillColor
            .Font.ColorIndex = fontColor
        End With
    End With
    target.Parent.Protect password:=Strings.Mypw, userinterfaceonly:=True
End Sub

All of the cells in the ScannedPartNumbers named range have turned red, but I haven't yet been able to find a single cell that has the .Interior.ColorIndex or .Interior.Color value that even remotely resembles red!

Help please?

Upvotes: 2

Views: 2978

Answers (1)

Werrf
Werrf

Reputation: 1148

Think of Conditional Formatting as a sheet of transparency that's laid over the top of your cell formats. Conditional formatting doesn't actually change the interior colour of the cell, it places a new colour over the top of it and forces Excel to print that colour instead.

The result is that the cells Color and ColorIndex values do not change, so VBA checking them will not see any difference.

Rather than looking at the colour of the cells, may I suggest using the same conditional logic you're using for Conditional Formatting to check which cells you want to work with?

Colour options in Excel are strictly there for display purposes, and generally should not be seen as values. You can't sort or filter by colour, for good reason. While it is perforce possible to do something of the sort with VBA, it's rarely a good idea, and generally better to encourage users to use values to sort and filter by, rather than using colours.

Upvotes: 3

Related Questions