如何在特定单元格更改时运行Excel宏? [新转]

时间:2012-07-17 20:22:46

标签: excel vba excel-vba

我用Google搜索了,我编写了以下代码,只有在特定单元格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,则应发送一封电子邮件。此代码不会发送电子邮件案例: - (

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

试试这个:


Private Sub Worksheet_Change(ByVal Target As Range)

Static varD4_old As Variant ' Static variables retain their value between calls

Dim varD4 As Variant

varD4 = Range("D4").Value

If varD4 <> varD4_old Then     Debug.Print "D4 changed from " & varD4_old & " to " & varD4     varD4_old = varD4   ' NOW RUN MY CHANGE CODE End If

End Sub