Search code examples
excelvbacolorscell

How to change cells colors in specified columns?


I picked up this code to select and change the interior color (green) of the EntireRow when the AtiveCell is behind the 6 Row.

I need to select and change the interior color (Color = 9359529) of the column "I" and "J" of the Row where is the ActiveCell. Is similar to this code but do not need the entire row, just the columns I and J.

Dim lTarget As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   
    If Target.Row >= 6 Then
       
        If Not lTarget Is Nothing Then
            lTarget.EntireRow.Interior.ColorIndex = 0
        End If
        
        Target.EntireRow.Interior.Color = 9359529
        Set lTarget = Target

    End If

End Sub

Solution

  • Using just your example and what I think you're asking this is the simplest way to do what I think you're asking.

    You either have just one row in the selection - or you just want the first row changed

    This can be changed to use a Range object - but this is easy to understand

    Dim lTarget As Range
    Const TargetCol1    As Integer = 9
    Const TargetCol2    As Integer = 10
    
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
       
        If Target.Row >= 6 Then
            If Not lTarget Is Nothing Then
                lTarget.EntireRow.Interior.ColorIndex = 0
            End If
            
            Cells(Target.Row, TargetCol1).Interior.Color = 9359529
            Cells(Target.Row, TargetCol2).Interior.Color = 9359529
            
            Set lTarget = Target
        End If
    End Sub