Excel VBA使用多个附件发送电子邮件

所以我们要举办这个大型的活动,我有一个excel表,每个人的姓名,电子邮件地址以及他们的行程文件(有2个) Cells(x, 3)Cells(x, 4) 。 我想要做的就是沿着专栏向每个人发送一封包含所有信息的“个性化”电子邮件。

在代码中, for循环只能到3,因为我只是通过发送电子邮件给自己进行testing,不想最终得到1000封电子邮件:P

我不断收到一个运行时错误440(自动化错误)在我试图添加附件…不知道发生了什么事或如何补救任何帮助表示赞赏

 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 x As Long Set olApp = CreateObject("Outlook.Application") 'Create e-mail item Set objMail = olApp.CreateItem(0) filePath = "\\fileserver\homeshares\Tsee\My Documents\Metropolitan Sales\MNF" subject = "Important Travel Information for MNF Event this weekend" x = 1 For x = 1 To 3 head = "<HTML><BODY><P>Hi " & Cells(x, 1).Value & ",</P>" body = 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>" body = body & "<BR /><P>Please find attached your travel information packet that contains important addresses and confirmation numbers. Please read through it and let me know if you have any questions.</P>" body = body & "<BR /><P>If you need to reach me this weekend, please call my cell phone <STRONG>(631) 793-9047</STRONG> or email me.</P>" body = body & "<BR /><P>Thanks,<BR />Liz</P></BODY></HTML>" With objMail .subject = subject .To = Cells(x, 2).Value .Attachments.Add = filePath & "/" & Cells(x, 3).Value .Attachments.Add = filePath & "/" & Cells(x, 4).Value .BodyFormat = olFormatHTML .HTMLBody = head & body .Send End With Next x End Sub 

除上述评论之外,@ bamie9l已经解决了你的一个问题

问题2

@ bamie9l太棒了! 这工作,但现在在.BodyFormat = olFormatHTML行我得到运行时错误“5”:无效的过程调用或参数 – metsales 13分钟前

您从Excel中拖曳Outlook, olFormatHTML是一个Outlook常量,因此Excel无法识别它。 在MS-Outlook的Immediate Window ,如果你键入?olFormatHTML那么你会注意到这个常量的值是2

在这里输入图像说明

因此,我们必须在Excel中声明这个常量。 就像我刚才提到的那样,你可以把Const olFormatHTML = 2放在代码的顶部,或者用.BodyFormat = 2replace.BodyFormat = olFormatHTML

问题3

@SiddharthRout所以这样的作品,但现在我得到一个疯狂的自动化错误…它通过循环一次..发送1电子邮件,然后当它起床.subject =主题我得到运行时错误“-2147221238(8004010a )':自动化错误,据我所知与运行时错误440 – metsales相同

问题是你正在循环之外创buildOutlook项目

 Set objMail = olApp.CreateItem(0) 

Outlook已经发送了这封电子邮件,现在为了下一封电子邮件,您将不得不重新创build它。 所以在循环内部移动该行。

 For x = 1 To 3 Set objMail = olApp.CreateItem(0) head = "<HTML><BODY><P>Hi " & Cells(x, 1).Value & ",</P>" Body = "Blah Blah" With objMail .subject = subject .To = Cells(x, 2).Value .Attachments.Add = FilePath & "/" & Cells(x, 3).Value .Attachments.Add = FilePath & "/" & Cells(x, 4).Value .BodyFormat = olFormatHTML .HTMLBody = head & Body .Send End With Next x