简体   繁体   中英

Worksheet_change: i do not want it to activate when value in cell does not change

Currently, I am using worksheet_change to automatically change cell colours when a user makes any changes to a cell's value. However, my else clause runs when a user enters and leaves a cell without changing the cell's value (User probably double clicked a cell, then clicked on a different cell instead of pressing escape.) . How can I amend my code so that the Else clause only runs if the user has made changes to the cell's value?

Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("A1:Z200")) Is Nothing Or Target.Cells.Count > 1 Then

Exit Sub

Else

Range(Target.Address).Interior.ColorIndex = 43

End If

You either have to:

  1. Educate users to push Escape rather than Enter if they have gone into Edit mode but have changed their mind; or
  2. Make a copy of the range, check the value against the copy and if they've made changes, update the copy with the new value and change the original cell color.

Please give this a try...

Dim oVal
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, Range("A1:Z200")) Is Nothing Then
    If Target <> oVal Then
        Range(Target.Address).Interior.ColorIndex = 43
        oVal = Target
    End If
End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Target, Range("A1:Z200")) Is Nothing Then
    oVal = Target.Value
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