简体   繁体   中英

If activecell interior color changes then

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

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

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