Home > Software engineering >  How to make VBA code to change cells colors?
How to make VBA code to change cells colors?

Time:04-01

i pick up this code that select and change the interior color (green) of the EntireRow when the ativecell is behind the 6 Row. I need to change this code 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. Can anyone help me?

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

CodePudding user response:

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

CodePudding user response:

A Worksheet SelectionChange

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Row < 6 Then Exit Sub
    Target.EntireRow.Columns("I:J").Interior.Color = 9359529
End Sub
  • If you need to remove any previous color in the rows, use the following.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Row < 6 Then Exit Sub
    With Target.EntireRow
        .Interior.ColorIndex = xlNone
        .Columns("I:J").Interior.Color = 9359529
    End With
End Sub
  • Related