2012-07-17 28 views
2

我GOOGLE了四周,我寫了下面的代碼,我想只能運行在特定的細胞,D4,變化:如何在特定單元更改時運行我的Excel宏? [新的轉折]

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在這種情況下,該代碼將無法發送電子郵件:-(

不郵件應該送任何人都知道如何解決這個

+0

除了'worksheet_change'之外,您還必須處理'worksheet_calculate'事件 – 2012-07-17 20:35:53

+0

請參閱http://stackoverflow.com/questions/11406628/vba-code-doesnt-run-when-cell-is-changed-by -a-式/ 11409569#11409569 – 2012-07-17 21:22:31

回答

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 
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

相關問題