如何使用 Worksheet_change 事件更改单元格值而不触发第二次调用
How to change cell value using Worksheet_change event without triggering a second call
我正在处理一个简单的工作表,我需要根据用户输入更改单元格中的一些数据;这些更改是使用 Worksheet_Change
事件进行的。但是,当我改变另一个单元格时,事件又被触发了,所以很头疼(这是一种"chicken-and-egg"场景)。
示例:
private sub Worksheet_Change(ByVal Target as Range)
with target ' Only cells in column C are unlocked and available for edition
select case .row
case 4
if .value = 1 then
ActiveSheet.cells(5,3).value = 0
else
ActiveSheet.cells(5,3).value = 1
end if
case 5
if .value = 1 then
ActiveSheet.cells(4,3).value = 0
else
ActiveSheet.cells(4,3) = 1
end
end select
end with
end sub
如您所见,第 4 行的更改会触发第 5 行的更改,这可能会触发第 4 行的另一个更改...并且它变成了 "infinite call",最终崩溃 excel。
所以,问题是:有没有办法以编程方式更改单元格的值而不触发Worksheet_Change
事件?
在更改单元格时禁用中断,然后在完成后重新启用它们:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range
Set A = Range("A1")
If Intersect(Target, A) Is Nothing Then Exit Sub
Application.EnableEvents = False
A.Value = ""
A.Offset(0, 1).Value = "CLEARED"
Application.EnableEvents = True
End Sub
我正在处理一个简单的工作表,我需要根据用户输入更改单元格中的一些数据;这些更改是使用 Worksheet_Change
事件进行的。但是,当我改变另一个单元格时,事件又被触发了,所以很头疼(这是一种"chicken-and-egg"场景)。
示例:
private sub Worksheet_Change(ByVal Target as Range)
with target ' Only cells in column C are unlocked and available for edition
select case .row
case 4
if .value = 1 then
ActiveSheet.cells(5,3).value = 0
else
ActiveSheet.cells(5,3).value = 1
end if
case 5
if .value = 1 then
ActiveSheet.cells(4,3).value = 0
else
ActiveSheet.cells(4,3) = 1
end
end select
end with
end sub
如您所见,第 4 行的更改会触发第 5 行的更改,这可能会触发第 4 行的另一个更改...并且它变成了 "infinite call",最终崩溃 excel。
所以,问题是:有没有办法以编程方式更改单元格的值而不触发Worksheet_Change
事件?
在更改单元格时禁用中断,然后在完成后重新启用它们:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range
Set A = Range("A1")
If Intersect(Target, A) Is Nothing Then Exit Sub
Application.EnableEvents = False
A.Value = ""
A.Offset(0, 1).Value = "CLEARED"
Application.EnableEvents = True
End Sub