Reputation: 37
I want the following VBA code:
If the activecell interior color changes to colorindex 44 then I want the cell five columns to the right to have the text "Done" and today's date.
I have tried the below but only works when I move the selected cell to the right. It also does not stop working when a cell color is NOT changed.
Private Sub Worksheet_SelectionChange (ByVal Target As Range)
If ActiveCell.Offset(0, -1).Interior.ColorIndex = 44 Then
ActiveCell.Offset(0, 4) = "Done" & Date
End If
End Sub
Upvotes: 1
Views: 870
Reputation: 57693
You must use Target
instead of ActiveCell
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Interior.ColorIndex = 44 Then
Target.Offset(ColumnOffset:=4).Value = "Done " & Date
End If
End Sub
Note that this cannot check if the color was changed or not as there is no event for that. You can only test if the actual color index is 44. But to prevent overwriting the "change" date you can just test if the date already exists.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Rows.Count + Target.Columns.Count > 2 Then Exit Sub 'exit if more than one cell is selected
If Target.Interior.ColorIndex = 44 And Not Left$(Target.Offset(ColumnOffset:=4).Value, 4) = "Done" Then
Target.Offset(ColumnOffset:=4).Value = "Done " & Date
End If
End Sub
Upvotes: 4