QP School
Format cells with conditional formatting in 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: Format cells with conditional formatting in VBA (/showthread.php?tid=5246)



Format cells with conditional formatting in VBA - Qomplainerz - 07-27-2023

Example:

Sub ApplyConditionalFormatting()
    Dim rng As Range
   
    'Specify the range where conditional formatting should be applied
    Set rng = Range("B2:B10")
   
    'Apply conditional formatting based on cell values
    With rng.FormatConditions.Add(Type:=xlCellValue, Operator:=xlBetween, Formula1:="5", Formula2:="8")
        .Interior.Color = RGB(255, 255, 0) 'Yellow color
    End With
End Sub

Explanation:

The code defines a subroutine named ApplyConditionalFormatting.
It declares a variable rng to store the range of cells where conditional formatting should be applied.
The Set statement is used to specify the range B2 to B10 as the range where conditional formatting will be applied.
The With statement is used to work with the FormatConditions object of the specified range.
The Add method is used to add a new conditional formatting rule.
The conditional formatting is based on cell values between 5 and 8 (inclusive). If a cell value falls within this range, the formatting inside the With block will be applied.
The interior color of the cells is set to yellow using the RGB function.