2

我四处搜索,并编写了以下代码,我只想在特定单元格 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 是一个公式,我也希望"=SUM(A4:C4)"它能够工作:所以如果 D4 是,那么如果总和低于 100,则应该发送一封电子邮件。在这种情况下,此代码不会发送电子邮件:-(

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

4

2 回答 2

4
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
于 2012-07-17T21:31:37.533 回答
0

那么,当任何贡献单元格发生变化时,您需要检查您的单元格。如果它们在同一张纸上,这将起作用:

试试这个:

Private Sub Worksheet_Change(ByVal Target As Range)

Static varD4_old As Variant ' 静态变量在调用之间保持其值

将 varD4 调暗为变体

varD4 = Range("D4").Value

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

结束子

于 2012-07-18T17:32:06.530 回答