Worksheet_Change triggers when a cell value is changed (which is what I want), but it also triggers when you enter a cell as if to edit it but don’t actually change the cell’s value (and this is what I don’t want to happen).
Say I want to add shading to cells whose value was changed. So I code this:
Private Sub Worksheet_Change(ByVal Target As Range)
Target.Interior.ColorIndex = 36
End Sub
Now to test my work: Change cell A1 and the cell gets highlighted. That’s the desired behaviour. So far so good. Then, double click B1 but don’t change the value there and then click C1. You’ll notice B1 gets highlighted! And this is not the desired behaviour.
Do I have to go through the methods discussed here of capturing the old value, then compare old to new before highlighting the cell? I certainly hope there’s something I’m missing.
I suggest automatically maintaining a “mirror copy” of your sheet, in another sheet, for comparison with the changed cell’s value.
@brettdj and @JohnLBevan essentially propose doing the same thing, but they store cell values in comments or a dictionary, respectively (and +1 for those ideas indeed). My feeling, though, is that it is conceptually much simpler to back up cells in cells, rather than in other objects (especially comments, which you or the user may want to use for other purposes).
So, say I have
Sheet1whose cells the user may change. I created this other sheet calledSheet1_Mirror(which you could create atWorkbook_Openand could set to be hidden if you so desire — up to you). To start with, the contents ofSheet1_Mirrorwould be identical to that ofSheet1(again, you could enforce this atWorkbook_Open).Every time
Sheet1‘sWorksheet_Changeis triggered, the code checks whether the “changed” cell’s value inSheet1is actually different from that inSheet1_Mirror. If so, it does the action you want and updates the mirror sheet. If not, then nothing.This should put you on the right track: