Home » excel » excel – Color Cell Based on Value in Cell

excel – Color Cell Based on Value in Cell

Posted by: admin May 14, 2020 Leave a comment

Questions:

Using a macro I have consolidated info from several workbooks into one sheet in new workbook.

In one column I have created a named range called ColRange. That column has numbers ranging from -350 to 500.

How do I change the color of the cells based on the value of the text in the cell.
red(0-500)
yellow(-5-0)
green(-350–5)

How to&Answers:

Have a look at conditional formatting. You may not even need VBA to do this.

That being said, the VBA code would look something like this:

Public Sub colorit()
    Dim colRange As Range
    Dim rowNum As Integer
    Dim rnum As Integer

    rnum = 20
    Set colRange = Range(Cells(2, 9), Cells(rnum, 9))

    For rowNum = 1 To colRange.Rows.Count
        If colRange.Cells(rowNum, 1).Value <= -5 Then
            colRange.Cells(rowNum, 1).Interior.Color = RGB(0, 255, 0)
        ElseIf colRange.Cells(rowNum, 1).Value <= 0 Then
            colRange.Cells(rowNum, 1).Interior.Color = RGB(255, 255, 0)
        ElseIf colRange.Cells(rowNum, 1).Value <= 500 Then
            colRange.Cells(rowNum, 1).Interior.Color = RGB(255, 0, 0)
        End If
    Next rowNum
End Sub

Answer:

Assume that value is the number stored in the column then:

If value >= 0 AND value <= 500 Then
    ColRange.Interior.Color = RGB(255,0,0)
ElseIf  value >= -5 Then
    ColRange.Interior.Color = RGB(255,255,200)
Else
    ColRange.Interior.Color = RGB(0,255,0)
End If

And assuming that values greater than 500 or less than -350 is either not possible or validated by your script. Also, your ranges overlap a bit, what color should 0 be? Red or Yellow?

Answer:

This is in response to the original question, it is a simple modification of Vincent’s response:

If it is a named range (using the UI: Insert, Name, Define):

Dim c As Range

For Each c In Range("ColRange").Cells
    If c.Value >= 0 And c.Value <= 500 Then
        c.Interior.Color = RGB(255, 0, 0)
    ElseIf c.Value >= -5 Then
        c.Interior.Color = RGB(255, 255, 200)
    Else
        c.Interior.Color = RGB(0, 255, 0)
    End If

Next c

If it is a range object, defined in the code:

Dim c as Range

For Each c In colRange.Cells

    If c.Value >= 0 And c.Value <= 500 Then
        c.Interior.Color = RGB(255, 0, 0)
    ElseIf c.Value >= -5 Then
        c.Interior.Color = RGB(255, 255, 200)
    Else
        c.Interior.Color = RGB(0, 255, 0)
    End If

Next c

I think Vincent’s response won’t quite work because, it attempts to operate on the entire ColRange range, inside the If Then, rather than operating on each cell one at a time. (For this reason, you may also want to wrap it with Application.ScreenUpdating = False