QP School

Full Version: Change cell colors based on values with VBA
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Example:

Sub ColorCellsBasedOnValue()
    Dim cell As Range

    'Loop through each cell in column B
    For Each cell In Range("B1:B10")
        If cell.Value > 5 Then
            cell.Interior.Color = RGB(255, 0, 0) 'Red color for values greater than 5
        Else
            cell.Interior.Color = RGB(0, 255, 0) 'Green color for values less than or equal to 5
        End If
    Next cell
End Sub

Explanation:

The code defines a subroutine named ColorCellsBasedOnValue.
It declares a variable cell of type Range, which will be used to loop through each cell in column B.
The For Each loop iterates through each cell in the range Range("B1:B10").
The If statement checks the value of each cell. If the value is greater than 5, the background color of the cell is changed to red using the RGB function (255, 0, 0). Otherwise, if the value is less than or equal to 5, the background color is changed to green (0, 255, 0).