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

问题描述 投票:0回答:2

因此,我的代码循环遍历一系列单元格并触发电子邮件,条件是在此示例中,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
excel vba excel-vba
2个回答
0
投票

您正在从N145:N160循环,但仅检查Range(“N150”)= Range(“F150”)。如果该检查为真,则在第一次迭代时,当cll为N145时将为真,因此发送电子邮件并退出循环,因此不会处理其他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   
...

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传递给函数之前观察它的价值,从而使您的调试过程变得更加容易。

© www.soinside.com 2019 - 2024. All rights reserved.