Search code examples
excelvbacolorscell

Automatically Changing Cell Background Colors Excel VBA


So basically I want a code that can change color of cells. For example, if A1 = 1 and B1 = 3%, 54% or 5% then change B1's background color to green. Else if B1 = 1% or 2% change colors to red.

This is what I have so far, I cant seem to figure it out. Any help will be greatly appreciated.

Sub color()
  Range("A1:B1").Formula = " = If(A1 = 1 AND B1 =3%,Range("A1:B1").Interior.ColorIndex = 4)"
End Sub

Solution

  • I think you can figure out how the code below works and make necessary changes

    
    Sub color()
    
      Dim ws As Worksheet
      Dim r As Range, c As Range
      Set ws = ThisWorkbook.ActiveSheet
    
      With ws
        Set r = Range("A1").CurrentRegion
      End With
    
      For Each c In r
        If c.Value = 1 And ((c.Offset(, 1) = 0.03) Or (c.Offset(, 1) = 0.54) Or (c.Offset(, 1) = 0.05)) Then
          Range(c, c.Offset(, 1)).Interior.ColorIndex = 4
        ElseIf c.Value = 1 And ((c.Offset(, 1) = 0.01) Or (c.Offset(, 1) = 0.02)) Then
          Range(c, c.Offset(, 1)).Interior.ColorIndex = 3
        End If
      Next
    
    End Sub