用我的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Set Target = Me.Range("D10", "D17")
Dim KeyCells As Range
Set KeyCells = Range("D10", "D17")
If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
If Range("D10").Value < 31.35 Then
Ans = msgbox("The accumulated Rain fall for this week is insuficient." & vbNewLine & "Click Yes if it was irrigated" & vbNewLine & "Click No if not", vbYesNo + vbCritical, "Rainfall Insufficient")
End If
End If
Select Case Ans
Case vbYes
Range("E10").Value = "Yes"
Exit Sub
Case vbNo
Range("E10").Value = "No"
Exit Sub
End Select
End Sub
消息框多次出现,但当我对Select Case
发表评论时,它会消失。
为什么?
答案 0 :(得分:0)
您的代码存在一些问题。我将详细说明我认为存在的问题,然后就正确的重写提出建议。
Set Target = Me.Range("D10", "D17")
错了。 目标会被传递到Worksheet_Change事件宏,因为已接收新值的一个或多个单元格已修改其值或已删除其值。关键是哪些细胞已经改变,将Target设置为其他东西会破坏它。If Not Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
没有任何意义。当然他们会相交。他们是一回事。Select Case Ans
如果可以修复包含Intersect method的If语句,则此Select Case statement属于 If Intersect Then语句。Set KeyCells = Range("D10", "D17")
通常情况下,在我知道自己需要之前,我从不宣布,分配或设置任何内容。与Select Case一样,它属于If Intersect Then语句。Range(Target.Address)
如果我们单独离开Target(请参阅上面的#1),那么这与说Target
相同。Application.EnableEvents = False
关闭事件,否则您将触发另一个事件,宏将尝试在其自身上运行这是我对你所尝试的最好的猜测。
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("D10", "D17"), Target) Is Nothing Then
On Error GoTo bm_Safe_Exit
Application.EnableEvents = False
Dim ans As Long, KeyCells As Range
Set KeyCells = Range("D10", "D17") '<~~ this is completely unnecessary now.
If Not Application.Intersect(Range("D10"), Target) Is Nothing Then
If Range("D10").Value < 31.35 Then
ans = MsgBox("The accumulated Rain fall for this week is insuficient." & vbNewLine & _
"Click Yes if it was irrigated" & vbNewLine & _
"Click No if not", _
vbYesNo + vbCritical, "Rainfall Insufficient")
Select Case ans
Case vbYes
Range("E10").Value = "Yes"
Case vbNo
Range("E10").Value = "No"
End Select
End If
End If
If Not Application.Intersect(Range("D17"), Target) Is Nothing Then
'do something for when it was D17 that changed here
End If
End If
bm_Safe_Exit:
Application.EnableEvents = True
End Sub
当D17收到更改时,您可能想要对我离开的区域做些什么。如果不重新打开Application.EnableEvents property,或者所有事件宏都将停止“触发”,请不要退出子。
答案 1 :(得分:-1)
Worksheet_Change事件发生在单元格选择的更改上。
范围(E10)的选择案例编辑值,因此workheet_change事件再次发生,它将成为事件处理的递归调用。