How do you fill a cell with color based on a condition?

Hello…!
I want to fill the colour in excel cell according to condition for the multiple rows i have excel sheet with four columns and i want to fill the colour in marks column where i want green colour where marks are greater than 80 and red colour where marks are less than 80, please refer attached sheet.
Task1.xlsx (9.2 KB)

Hi @Ranjit_Mhetre

Please refer below threads , hope it helps .

Hi @Ranjit_Mhetre

Please use the below macros:

Sub ColorColumnBasedOnValue()
    Dim ws As Worksheet
    Dim rng As Range
    Dim cell As Range
    Dim columnLetter As String
    Dim lastRow As Long
 
    ' Set the worksheet and column you want to format
    Set ws = ThisWorkbook.Sheets("May") ' Change "Sheet1" to your sheet name
    columnLetter = "D" ' Change this to your target column letter
 
    ' Find the last row with data in the specified column
    lastRow = ws.Cells(ws.Rows.Count, columnLetter).End(xlUp).Row
 
    ' Define the range to format
    Set rng = ws.Range(columnLetter & "1:" & columnLetter & lastRow)
 
    ' Loop through each cell in the specified range
    For Each cell In rng
        If IsNumeric(cell.Value) Then
            If cell.Value > 80 Then
                cell.Interior.Color = RGB(0, 255, 0) ' Green color
            ElseIf cell.Value <= 80 Then
                cell.Interior.Color = RGB(255, 0, 0) ' Red color
            End If
        Else
            cell.Interior.ColorIndex = xlNone ' Clear any existing color if not numeric
        End If
    Next cell
End Sub

I have attached the xaml also for your reference please check:
Sequence43.xaml (8.9 KB)
Task1.xlsx (9.3 KB)
Sample.txt (1.1 KB)

Regards

@Ranjit_Mhetre

Sub ColorMarks()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim marksColumn As String
    marksColumn = "D" ' Change this to your marks column if it's different

    ' Set the worksheet
    Set ws = ThisWorkbook.Sheets("May") ' Change to your sheet name

    ' Find the last row with data in the Marks column
    lastRow = ws.Cells(ws.Rows.Count, marksColumn).End(xlUp).Row

    ' Loop through each row in the Marks column
    For i = 2 To lastRow ' Assuming the data starts from row 2
        If IsNumeric(ws.Cells(i, marksColumn).Value) Then
            If ws.Cells(i, marksColumn).Value > 80 Then
                ws.Cells(i, marksColumn).Interior.Color = RGB(0, 255, 0) ' Green color
            Else
                ws.Cells(i, marksColumn).Interior.Color = RGB(255, 0, 0) ' Red color
            End If
        End If
    Next i
End Sub


image

Hi @Ranjit_Mhetre,

Please find the attached XAML file that works for your scenario. Make sure to update the Excel file path accordingly.


Main.xaml (14.0 KB)

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.