简体   繁体   中英

Excel VBA - Cell color Change

I am trying to write a macro that changes colors based on a value in Column L. If the cell in Column L is YES, then Hightlight Column B cell in Red. However, the Macro below doesn't work or fail. It runs but does nothing.

   Sub ColorMeElmo()
   Dim i As Long, r1 As Range, r2 As Range
   For i = 2 To 5
   Set r1 = Range("L" & i)
   Set r2 = Range("B" & i & ":B" & i)
   If r1.Value = "YES" Then r2.Interior.Color = vbRed
   Next i
   End Sub 

Put this in Sheet you want to watch.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim CCell As Range
    Dim sht As Worksheet
    Set CCell = Range("L:L")
    Set sht = Worksheets("Sheet1") 'EDIT
    If Target.Count = 1 Then
        If Not Application.Intersect(CCell, Range(Target.Address)) _
            Is Nothing Then
                If Target.Value = "YES" Then
                    sht.Cells(Target.Row, 2).Interior.Color = RGB(255, 0, 0)
                End If
        End If
    End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim CCell As Range
    Dim sht As Worksheet
    Set CCell = Range("L:L")
    Set sht = Worksheets("SheetName") 
    If Target.Count = 1 Then
        If Not Application.Intersect(CCell, Range(Target.Address)) _
            Is Nothing Then
                If Target.Value = "YES" Then
                    sht.Cells(Target.Row, 2).Interior.Color = RGB(255, 0, 0)
                End If
        End If
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM