将新行添加到表时,将EXCEPT运行代码

我有一小段代码监视'Y'列中的单元格以进行更改,如果有更改,则会运行代码的主要位。

是否有可能像平常一样运行代码除了添加新行? (也就是说,如果用户右键单击左侧的行号并单击“插入” – 我不希望代码在用户眼中运行,但没有任何内容添加到列Y中的单元格中。

这里是代码:

Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Range("Y2:Y5000"), Target) Is Nothing Then Call Reminder End If End Sub 

如果你需要看到更多的代码,那么请说。

谢谢

你不能阻止事件的运行,但你可以忽略整行被插入的情况。

 Sub Worksheet_Change(ByVal Target As Range) If Target.Columns.Count < Me.Columns.Count Then ' Your existing code here End If End Sub 

这是一个可能的解决scheme。 它是基于捕捉范围的前一个状态,因此如果添加一个新行,过去与现在的范围不同。 不是我做的最好的代码,但你会得到这个想法,并会知道如何调整它。 请记住将其存储在工作表对象中:

 'use global to store the address of current range Dim myRange As Range Private Sub Worksheet_Activate() 'have to initialize the global before first usage Set myRange = Range("Y2:Y5000") End Sub Private Sub Worksheet_Change(ByVal Target As Range) Dim tempRange As Range Set tempRange = Range("Y2:Y5000") 'compare the range addresses, if don't match (won't match when adding a row or column because the myRange address has changed) If Not Intersect(tempRange, Target) Is Nothing And myRange.Address = tempRange.Address Then Call Reminder End If 'reset the range of global Set myRange = tempRange End Sub