通过VBA附加多个文件

时间:2018-02-08 05:57:33

标签: excel vba excel-vba

有人可以帮我编辑下面的脚本,添加电子表格第3栏(C栏)上列出的多个文件吗?

我当前的宏一次查找一个文件并发送单个电子邮件。我需要它来查找列C(第3列)中列出的多个文件名(在列出的文件夹路径中)并执行此操作直到它到达空单元格。

我当前的脚本位于下面,您将看到它一次查找一个文件。

Sub AttachandSendEmail()
Dim obMail As Outlook.MailItem
Dim irow As Integer
Dim dpath As String
Dim pfile As String

'file path
dpath = "C:\Users\filelocation"

'looping through all the files and sending an mail

irow = 1

Do While Cells(irow, 3) <> Empty


'pikcing up file name from column C
 pfile = Dir(dpath & "\*" & Cells(irow, 3) & "*")


'checking for file exist in a folder and if its a pdf file

If pfile <> "" And Right(pfile, 3) = "pdf" Then

    Set obMail = Outlook.CreateItem(olMailItem)

    With obMail
        .To = "email@comapny.com"
        .Subject = "O/S Blanace"
        .BodyFormat = olFormatPlain
        .Body = "Please see attached files"
        .Attachments.Add (dpath & "\" & pfile)
        .Send
    End With

End If

'go to next file listed on the C column
 irow = irow + 1

Loop


End Sub

1 个答案:

答案 0 :(得分:1)

试试这个,它会发送一条包含所有文件的消息。

Set obMail = Outlook.CreateItem(olMailItem)
With obMail
    .To = "email@comapny.com"
    .Subject = "O/S Blanace"
    .BodyFormat = olFormatPlain
    .Body = "Please see attached files"

    Do While Cells(irow, 3) <> Empty
        'pikcing up file name from column C
        pfile = Dir(dpath & "\*" & Cells(irow, 3) & "*")
        'checking for file exist in a folder and if its a pdf file

        If pfile <> "" And Right(pfile, 3) = "pdf" Then
            .Attachments.Add (dpath & "\" & pfile)
        End If

        'go to next file listed on the C column
        irow = irow + 1
    Loop

    .Send
End With