特定单元格更改时如何运行我的Excelmacros?

我search了一下,我写了下面的代码,我只想在特定的单元格D4发生变化时运行:

Private Sub Worksheet_Change(ByVal Target As Range) Dim KeyCells As Range Static EmailSent As Boolean Dim Threshold As Integer Dim Cell As String, Email As String, Msg As String Cell = "D4" Threshold = 100 Email = Range("E7").Value Set KeyCells = Range(Cell) If Not Application.Intersect(Range(Cell), Range(Target.Address)) Is Nothing Then Dim x As Integer x = Range(Cell).Value If x >= Threshold Then EmailSent = False ElseIf x < Threshold And Not EmailSent Then EmailSent = True Msg = "You only have " & x & " widgets remaining." MsgBox Msg SendMail Email, Msg End If End If End Sub 

这工作,我知道这里有很多类似的问题。 但是在这里我遇到了麻烦:只有当我将D4设置为一个明确的值,比如说"48" ,这才有效。 即使D4是一个公式,我也希望它能够工作:所以如果D4是"=SUM(A4:C4)"那么如果总和低于100,就会发送一封电子邮件。这个代码在这种情况下不会发送电子邮件: (

有谁知道如何解决这一问题?

 Private Sub Worksheet_Calculate() CheckForMail End Sub Private Sub Worksheet_Change(ByVal Target As Range) CheckForMail Target End Sub Sub CheckForMail(Optional rng As Range = Nothing) Static EmailSent As Boolean Dim KeyCells As Range Dim Threshold As Integer Dim Cell As String, Email As String, Msg As String Dim x As Integer Cell = "D4" Set KeyCells = Me.Range(Cell) 'if called from worksheet_change, check the range If Not rng Is Nothing Then If Application.Intersect(KeyCells, rng) Is Nothing Then Exit Sub End If End If Threshold = 100 Email = Me.Range("E7").Value x = KeyCells.Value If x >= Threshold Then EmailSent = False ElseIf x < Threshold And Not EmailSent Then EmailSent = True Msg = "You only have " & x & " widgets remaining." MsgBox Msg SendMail Email, Msg End If End Sub 

那么,当任何一个有贡献的细胞发生变化时,你需要检查你的细胞。 如果他们在同一张纸上,这将工作:

尝试这个:


私人小组Worksheet_Change(BYVAL目标作为范围) 

静态varD4_old As Variant'静态variables在调用之间保持其值

Dim varD4 As Variant

varD4 =范围(“D4”)

如果varD4 <> varD4_old那么
Debug.Print“D4从”&varD4_old&“更改为”&varD4
varD4_old = varD4
“现在运行我的更改代码
万一

结束小组