VBA使用IF公式添加附件

时间:2014-11-16 12:17:29

标签: excel vba excel-vba

我尝试对此进行编码,以便根据收件人的不同来向不同附件发送电子邮件。不幸的是每次我在ELSE END IF

上获得自动化错误
Sub CreateHTMLMail()
'Creates a new e-mail item and modifies its properties.

    Dim olApp As Object
    Dim objMail As Object
    Dim body, head, filePath, subject As String
    Dim xyz As Long
    Set olApp = CreateObject("Outlook.Application")
    'Create e-mail item
    x = 1

    filePath = "C:\Users\user\Desktop\Nowy folder\"
    subject = "yyyyyyyyyyyyyyyyyyyyy"

    For xyz = 1 To 4
        ActiveSheet.Range("f5").Select
        ActiveCell.FormulaR1C1 = xyz
        Set objMail = olApp.CreateItem(0)
        head = "<HTML><BODY><P>Hi " & Cells(xyz, 1).Value & ",</P>"
        body = "<BR /><P>We are looking forward to having you at our <STRONG>Metropolitan Night Football Event</STRONG> this upcoming Sunday, <STRONG>11/17</STRONG>!  Note, that the Giants game time has changed from 8:30 PM to 4:25 PM.</P>"
        With objMail
            .subject = subject
            .To = ActiveSheet.Range("To")
            If Range("f5").Value = "1" Then
                .Attachments.Add = filePath & "123 1 tej"
            Else
            End If
            If Range("f5").Value = "2" Then
                .Attachments.Add = filePath & "123 2 tej"
            Else
            End If
            If Range("f5").Value = "3" Then
                .Attachments.Add = filePath & "123 3 tej"
            Else
            End If
            If Range("f5").Value = "4" Then
                .Attachments.Add = filePath & "123 4 tej"
            End If
            .BodyFormat = 2
            .HTMLBody = head & body
            .display
        End With
    Next xyz
End Sub

1 个答案:

答案 0 :(得分:2)

ElseIf不遵循EndIf

它的If,ElseIf,EndIf

If Range("f5").Value = "1" Then
       .Attachments.Add = filePath & "123 1 tej"

Elseif Range("f5").Value = "2" Then
       .Attachments.Add = filePath & "123 2 tej"

ElseIf Range("f5").Value = "3" Then
       .Attachments.Add = filePath & "123 3 tej"

ElseIf Range("f5").Value = "4" Then
       .Attachments.Add = filePath & "123 4 tej"
EndIf

您也可以在这种情况下使用Select Case(代码更少,更整洁)

Select Case Range("f5").Value

       Case 1
               .Attachments.Add = filePath & "123 1 tej"
       Case 2
               .Attachments.Add = filePath & "123 2 tej"
       Case 3
               .Attachments.Add = filePath & "123 3 tej"
       Case 4
               .Attachments.Add = filePath & "123 4 tej"

 End Select

但是对于你写的最小的代码

 .Attachments.Add = filePath & "123 " &  Range("f5").Value & " tej"