Excel VBA从具有文件路径的单元格附加多个文件

时间:2018-07-13 05:56:32

标签: excel-vba outlook-vba

我有代码可以根据在Excel中创建的表中的值创建自动电子邮件。该代码仅附加单元格值中的1个文件。如果在同一单元格或下一列中有多个文件,那么对于VBA领域的新手来说,我会迷失在如何实现这一点上。感谢任何人都可以提供帮助。

以下是我的代码:-

 Sub SendEmailWithAttachmentAndBody()

'Created by Mirat for ****.
'This code will autocreate emails along relevant attachents. User needs to create a master data file to include following fields in respective columns.
'To = Column A.
'CC = Column B.
'Bcc = Column C.
'Subject = Column D.
'Body = Column E.
'Attachment = Column F.
'Only 1 file can be attached for now.

Dim OlAPP As Outlook.Application
Dim OlMail As Outlook.MailItem

For i = 2 To Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
    Set OlAPP = New Outlook.Application
    Set OlMail = OlAPP.CreateItem(olMailItem)

    MailAttachment = Application.Cells(i, 6).Value

    With OlMail
    .Display
    End With
        Signature = OlMail.Body

    With OlMail
    .To = Cells(i, 1).Value
    .CC = Cells(i, 2).Value
    .BCC = Cells(i, 3)
    .Subject = Cells(i, 4).Value
    .HTMLBody = Cells(i, 5).Value & "<br>" & .HTMLBody
    .Attachments.Add MailAttachment

    .Display

    End With

    Set OlMail = Nothing
    Set OlAPP = Nothing
Next


End Sub

1 个答案:

答案 0 :(得分:0)

为回答您的问题,我假设F列中的附件存储为逗号分隔的字符串。

考虑到这一点,我将使MailAttachment成为变量变量并执行以下操作:

MailAttachment = Split (Application.Cells(i, 6).Value, ",")

然后在代码后面,我将遍历此数组并附加每个文件。

For each item in MailAttachment
.Attachments.Add item
Next

应该可以解决问题。