嵌套的IF可通过VBA发送电子邮件

时间:2019-06-13 09:39:09

标签: excel vba outlook excel-2010 outlook-vba

我正在尝试完成一些VBA,以便根据设置的标准(1、2或3)向其他人发送电子邮件。

我可以通过第一部分获得要在IF上发送的电子邮件,但是不能包含不同的条件。

    Dim OutlookApp As Object
    Dim OutlookMail As Object
    Set OutlookApp = CreateObject("Outlook.Application")
    Set OutlookMail = OutlookApp.CreateItem(0)

    If Sheets("Master").Range("D18") = 1 Then
        ActiveWorkbook.Save
        On Error Resume Next
        With OutlookMail
            .To = "x1@1.co.uk"
            .CC = "x1@1.co.uk"
            .BCC = ""
            .Subject = "Holiday Response"
            .Body = "Hi, please find attached the requested Holiday thank you." & vbNewLine & Signature
            .Attachments.Add Application.ActiveWorkbook.FullName
            .Send

    ElseIf Sheets("Master").Range("D18") = 2 Then
        ActiveWorkbook.Save
        On Error Resume Next
        With OutlookMail
            .To = "x2@2.co.uk"
            .CC = "x2@2.co.uk"
            .BCC = ""
            .Subject = "Holiday Response"
            .Body = "Hi, please find attached the requested Holiday thank you." & vbNewLine & Signature
            .Attachments.Add Application.ActiveWorkbook.FullName
            .Send

    Else
        ActiveWorkbook.Save
        On Error Resume Next
        With OutlookMail
            .To = "x3@3.co.uk"
            .CC = "x3@3.co.uk"
            .BCC = ""
            .Subject = "Holiday Response"
            .Body = "Hi, please find attached the requested Holiday thank you." & vbNewLine & Signature
            .Attachments.Add Application.ActiveWorkbook.FullName
            .Send
        End With

        Set OutlookMail = Nothing
        Set OutlookApp = Nothing
    End If
End Sub

电子邮件将根据满足的不同标准发送给不同的人。

错误消息当前显示“编译错误:没有If的其他情况”

1 个答案:

答案 0 :(得分:4)

您在代码中缺少一些End With。您还可以避免重复所有这些不必要的代码行,并进行一些简化。这将起作用:

Dim OutlookApp As Object
Dim OutlookMail As Object
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)

ActiveWorkbook.Save

With OutlookMail
    .BCC = ""
    .Subject = "Holiday Response"
    .Body = "Hi, please find attached the requested Holiday thank you." & vbNewLine & Signature
    .Attachments.Add Application.ActiveWorkbook.FullName

    If Sheets("Master").Range("D18") = 1 Then
        .To = "x1@1.co.uk"
        .CC = "x1@1.co.uk"
    ElseIf Sheets("Master").Range("D18") = 2 Then
        .To = "x2@2.co.uk"
        .CC = "x2@2.co.uk"
    Else
        .To = "x3@3.co.uk"
        .CC = "x3@3.co.uk"
    End If

    'Here use a proper error handling
    'On Error Resume Next
    .Send
End With

Set OutlookMail = Nothing
Set OutlookApp = Nothing
  

注意:如前所述,在发送邮件失败的情况下,您需要实施适当的error handling

希望这会有所帮助。