VBA使用IF公式添加附件

我试图编码这个发送邮件到不同的附件,取决于它是什么地址的许多地址。 不幸的是每次我在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 

否则如果不遵循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(代码较less,整洁)

 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"