Aleksei Nikolaevich
Aleksei Nikolaevich

Reputation: 325

How to highlight a cell in Excel using conditional if?

How can i conditionally assign color to cells ?

I have the following function that is supposed to assign different color to cells depending on the if statement:

 Function .....
    ..........
    If (IsNumeric(x)  Then
    .Color = 65344                  // does not work
    Else
    ...........
    End If
    End Function

How to do this in a correct way?

Upvotes: 0

Views: 3829

Answers (1)

Ross Brasseaux
Ross Brasseaux

Reputation: 4150

I'm not sure what color you are using here because 65344 isn't a hex value, but you can use RGB like this:

Function .....
    ..........
    Dim c As Range
    Dim report As Worksheet

    Set report = Excel.ActiveSheet
    Set c = report.Cells(1, 1)

    If IsNumeric(c.Value) Then
       c.Interior.Color = RGB(110, 110, 100)
    End If
End Function

Here is a better example that may help. (fyi this is free hand so double check it for syntax errors)

Sub changeColor()

Dim report as Worksheet

set report = Excel.ActiveSheet

dim i as integer

for i = 0 to 100
    if IsNumeric(report.cells(i,1).value) then
        report.cells(i,1).interior.color = rgb(220,230,241)
    else
        report.cells(i,1).interior.color = xlNone
    end if
next i
end sub

Upvotes: 2

Related Questions