VBA使用Worksheet_Calculate更改单元格时发送电子邮件

时间:2018-08-31 11:53:18

标签: excel vba excel-vba

因此,我的代码在一系列单元格中循环,并在此示例中N150 = F150的情况下触发了电子邮件。这有效,电子邮件已发送。但是我发现困难的是引用电子邮件正文中已更改的单元格。您可以在xMailBody变量中看到我尝试了cll.Offset(0,-12),因此,当N150 = F150时,我会在左侧获得12列的单元格值,该列应为B150。相反,我得到了正确的B145值,因为它是正确的列,但显然是不正确的行。我的目标范围是N145:N160,所以我认为它只是引用我范围内的第一行。几天来试图解决这个问题,将不胜感激!

Dim target As Range
Dim cll As Range

Private Sub Worksheet_Calculate()

    Set target = Range("N145:N160")

    For Each cll In target
        If (Range("N150") = Range("F150"))
            Call Mail_small_Text_Outlook(target)
            Exit For
        End If
    Next
End Sub
Sub Mail_small_Text_Outlook()
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xMailBody As String
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    xMailBody = "Hi there" & vbNewLine & vbNewLine & _
          cll.Offset(0, -12) & " has reached its target"

    On Error Resume Next
    With xOutMail
        .To = "email"
        .CC = ""
        .BCC = ""
        .Subject = "Target Reached"
        .Body = xMailBody
        .Send   'or use .Display
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub

2 个答案:

答案 0 :(得分:0)

您从N145:N160循环,但仅检查Range(“ N150”)= Range(“ F150”)。如果该检查为true,则在第一次迭代中cll为N145时为true,因此将发送电子邮件并退出循环,因此不会再处理其他cll。

...
Set target = Range("N145:N160")

For Each cll In target
    If cll = cll.offset(0, -12) then
        'cll is public, no need to pass it or target across
        Mail_small_Text_Outlook
        Exit For
    End If
Next   
...

答案 1 :(得分:0)

与其使用全局变量,不如在电子邮件中传递所需的值作为Mail_small_Text_Outlook函数的参数。

Dim target As Range

Private Sub Worksheet_Calculate()
    Dim FoundCell as String
    Set target = Range("N145:N160")

    For Each cll In target
        If (Range("N150") = Range("F150"))
            FoundCell = Cstr(cll.Offset(0, -12).Value2)
            Call Mail_small_Text_Outlook(FoundCell)
            Exit For
        End If
    Next
End Sub

Sub Mail_small_Text_Outlook(FoundCell as String)
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xMailBody As String
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    xMailBody = "Hi there" & vbNewLine & vbNewLine & _
          FoundCell & " has reached its target"

    On Error Resume Next
    With xOutMail
        .To = "email"
        .CC = ""
        .BCC = ""
        .Subject = "Target Reached"
        .Body = xMailBody
        .Send   'or use .Display
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub

现在,您可以在将FoundCell的值传递给函数之前观察它的值,从而使调试过程更加容易。