如何在Excel VBA中运行多个“For / Each”循环

我从Excel文档自动化VBA电子邮件附件脚本。 数据集看起来像这样

File Name Email Body Sample 1 john@ Hello! Sample 2 mary @ Hello! 

我想要做的是告诉excel在“email”列下为每个人创build一个电子邮件,然后将该文本写在电子邮件正文的“Body”列中,然后查找并附上名为在“文件名”栏下find。 所以John @会收到一封电子邮件,内容是“你好!” 和样品1附件。

这将需要三个单独的每个循环令我困惑:

这是我的代码到目前为止,但所有这一切是find附件:

 Sub Attachment() Dim colb As Range, mycell As Range, mycell2 As Range, mycell3 As Range Set colb = Range(Range("B2"), Range("B2").End(xlDown)) Set colc = Range(Range("C2"), Range("C2").End(xlDown)) Set cold = Range(Range("D2"), Range("C2").End(xlDown)) For Each mycell In colb Dim path As String path = mycell.Value Set OutApp = CreateObject("Outlook.Application") OutApp.Session.Logon Set OutMail = OutApp.CreateItem(0) Set myAttachments = OutMail.Attachments On Error Resume Next With OutMail .To = "" .CC = "" .BCC = "" .Subject = "Test" .Body = "" .Display End With On Error GoTo 0 myAttachments.Add "C:\R\" & path Set OutMail = Nothing Set OutApp = Nothing Next 

结束小组

我不是100%确定你在说什么,因为我没有看到3循环的需要。 你不能只是更新代码?

 With OutMail .To = mycell.Offset(0, 1).Text .CC = "" .BCC = "" .Subject = "Test" .Body = mycell.Offset(0, 2).Text .Display End With 

这将引用和抵消mycell获得收件人和正文

在这种情况下,您可以将整个程序切换到:

 Sub Attachment() Dim colb As Range, mycell As Range Set colb = Range(Range("B2"), Range("B2").End(xlDown)) For Each mycell In colb Set OutApp = CreateObject("Outlook.Application") OutApp.Session.Logon Set OutMail = OutApp.CreateItem(0) Set myAttachments = OutMail.Attachments On Error Resume Next With OutMail .To = mycell.Offset(0, 1).Text .Subject = "Test" .Body = mycell.Offset(0, 2).Text .Display End With myAttachments.Add "C:\R\" & mycell.Text Set OutMail = Nothing Set OutApp = Nothing Next End Sub