When you have a change event that works just fine on a single cell, you can make a few adjustments to ensure that it also works when you change a range of cells in one go, like when you paste three cells into A1 to A3
You may want to apply an approach similar to this:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet
Dim cel As Range
Dim myRow As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
If Not Intersect(Target, Range("A1:A3")) Is Nothing Then ' watch all the cells in this range
For Each cel In Target ' do the next steps for each cell that was changed
myRow = cel.Row
Range("B" & myRow).Value = "Changed " & Target.Row 'Just something specific to this cell. Not important
Application.EnableEvents = False
If IsEmpty(ws.Range("A" & myRow)) Then Sheet1.Range("A" & myRow).Value = 0
Application.EnableEvents = True
Next cel
End If
End Sub
Explanation:
If Not Intersect(Target, Range("A1:A3")) Is Nothing Then
-- only act on changes to cells A1 to A3
For Each cel In Target
- do the same thing for all cells that have been changed
Range("B" & myRow).Value = "Changed " & Target.Row
- enter some value into column B of the current row
In the next step of the macro we will possibly enter some data into the cells we are monitoring for a change, i.e. A1 to A3. A change in these cells will trigger this macro. This macro will write into the cells. A change in the cells will trigger this macro ....
You see where this is going. In order to avoid an endless loop, we turn off any event triggered macros, e.g. macros that fire when a cell is changed. So we turn off event monitoring with this statement.
Application.EnableEvents = False
- Now any events like "a cell has been changed" will be ignored.
We can now write a value into column A and that will not trigger the macro again. Great. We do whatever we need to do to cells A1 to A3 and then we turn event monitoring back on.
Application.EnableEvents = True
Then we go to the next cell (if any) in the range that triggered this macro.
Let me know if that helps or if you need a bit more detail. These things take a little learning curve.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…