在Excel 2016

时间:2018-01-16 20:31:32

标签: excel vba excel-vba email if-statement

是否有更有效的方法根据频繁更改的单元格值向用户发送电子邮件提醒?这是我正在处理的代码,以便你们能够理解问题的背景。

   'This is the main function

Sub notify()          
 Dim rng As Range
 For Each rng In Range("F3:F14")
    If (rng.Value = 1) Then
        Call mymacro
    End If
 Next rng

End Sub
-----------------------------------------------------------------------

  'This is the function that sends an email when called by the main function

  Private Sub mymacro()  
    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 & _
              "This is line 1" & vbNewLine & _
              "This is line 2"
    On Error Resume Next
    With xOutMail
        .To = "email address"
        .CC = ""
        .BCC = ""
        .Subject = "test succeeded"
        .Body = xMailBody
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub

说明:

上述两个代码都位于我的工作表的同一模块中。该代码非常适用于向用户发送电子邮件(通过Outlook)。例如,如果F3和F7评估为true,则会向用户发送两封电子邮件。

现在,问题是,如何编辑我的代码,如果出现相同的情况(F3和F7评估为true),发送给用户的两封电子邮件将指定哪个单元格评估为true 。换句话说,发送的每封电子邮件在指出哪个特定单元格被评估为真时会有所不同。

此外,如果更新单元格内的数据(" F3:F14"),代码是否能够重新运行?

我个人没有任何VBA背景,所以如果你们能够在外行的那个词中解释它会很好。谢谢!真的很感激! :)

1 个答案:

答案 0 :(得分:1)

在刷新查询时,代码应检查从F3到F14的每个单元格并查看它是否等于1,如果是,它将通过电子邮件向用户发送单元格位置。

更新:

'Need to be in the sheet code:
Private Sub Worksheet_Change(ByVal Target As Range)
    Call notify
End Sub

Sub notify()
    Dim rng As Range
    For Each rng In Range("F3:F14")
       If (rng.Value = 1) Then
           Call mymacro(rng.Address)
       End If
    Next rng
End Sub

Private Sub mymacro(theValue 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 & _
              "The value that changed is in cell: " & theValue
    On Error Resume Next
    With xOutMail
        .To = "email address"
        .CC = ""
        .BCC = ""
        .Subject = "test succeeded"
        .Body = xMailBody
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub