Change cell colors based on values with VBA - Printable Version +- QP School (https://qomplainerzschool.lima-city.de) +-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3) +--- Forum: Excel VBA Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=48) +--- Thread: Change cell colors based on values with VBA (/showthread.php?tid=5248) |
Change cell colors based on values with VBA - Qomplainerz - 07-27-2023 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). |