Forum Discussion

Excel's avatar
Excel
Iron Contributor
Dec 15, 2021

Loop in VBA code

Hello Everyone,

I am practice in VBA code. 

 

I want to highlight :

If any number is greater than 10, then it should highlight Red colour.

AND

If any number is greater than 20, then it should highlight Blue colour.

 

Please help..???

 

Here is a attached file..

2 Replies

  •  

    Public Sub FunWithLoop()
        Dim rng As Range
        Dim cel As Range
        ' Speed up execution by not updating the screen
        Application.ScreenUpdating = False
        ' Determine the used range in column A
        Set rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
        ' Remove the fill color
        rng.Interior.ColorIndex = xlColorIndexNone
        ' Loop through the cells of the range
        For Each cel In rng
            ' First check whether the value is greater then 20
            If cel.Value > 20 Then
                ' If so, color the cell blue
                cel.Interior.Color = vbBlue
            ' Else, check whether the value is greater than 10
            ElseIf cel.Value > 10 Then
                ' If so, color the cell red
                cel.Interior.Color = vbRed
            End If
        Next cel
        ' We're done, now show the result
        Application.ScreenUpdating = True
    End Sub

    Excel 

    • Excel's avatar
      Excel
      Iron Contributor
      It helps
      Thank you so much sir.

Resources