从多个电子邮件批量打印具有相同名称的附件

时间:2018-05-18 11:27:54

标签: vba printing outlook outlook-vba email-attachments

我在Outlook 2013中收到了电子邮件,每封邮件只附带一个名为“Report.pdf”的文件。

我正在尝试从我选择的电子邮件中批量打印所有附件。

如果附件都有不同的名称,我发现下面的代码有效。是否可以修改它以打印近150个具有相同名称的附件?

报告的名称无关紧要,因此请随意在代码中添加您需要的内容。

Sub BatchPrintAllAttachmentsinMultipleEmails()
Dim objFileSystem As Object
Dim strTempFolder As String
Dim objSelection As Outlook.Selection
Dim objItem As Object
Dim objMail As Outlook.MailItem
Dim objAttachments As Outlook.Attachments
Dim objAttachment As Outlook.Attachment
Dim objShell As Object
Dim objTempFolder As Object
Dim objTempFolderItem As Object
Dim strFilePath As String
Dim DateFormat

Set objFileSystem = CreateObject("Scripting.FileSystemObject")
strTempFolder = objFileSystem.GetSpecialFolder(2).Path & "\Temp for Attachments " & Format(Now, "YYYY-MM-DD_hh-mm-ss")
'Create a new temp folder
MkDir (strTempFolder)

Set objSelection = Outlook.Application.ActiveExplorer.Selection

For Each objItem In objSelection
    If TypeOf objItem Is MailItem Then
       Set objMail = objItem
       Set objAttachments = objMail.Attachments

       'Save all the attachments in the temp folder
       For Each objAttachment In objAttachments
           strFilePath = strTempFolder & "\" & objAttachment.FileName
           objAttachment.SaveAsFile (strFilePath)

           'Print all the files in the temp folder
           Set objShell = CreateObject("Shell.Application")
           Set objTempFolder = objShell.NameSpace(0)
           Set objTempFolderItem = objTempFolder.ParseName(strFilePath)
           objTempFolderItem.InvokeVerbEx ("print")
       Next objAttachment
    End If
Next
End Sub

1 个答案:

答案 0 :(得分:0)

如果所有附件都具有相同的名称,则不说为什么代码不起作用。我认为这是因为SaveAsFile想要在打印完成之前用下一个“Report.pdf”覆盖最后一个“Report.pdf”。

我的第一个想法是在Kill strFilePath之前添加SaveAsFile。经过反思,我认为这样做是行不通的,因为当你试图删除时,Shell仍然会打印之前的“Report.pdf”。

我认为最简单的方法是:

添加

Dim Count as Long

到你的Dims。

strFilePath = strTempFolder & "\" & objAttachment.FileName替换为:

Count = Count + 1
strFilePath = strTempFolder & "\" & Count & objAttachment.FileName

这将创建和打印名为“1Report.pdf”,“2Report.pdf”,“3Report.pdf”等文件。我使用了前缀而不是传统的后缀,因为它省去了在文件名和扩展名之间放置Count的麻烦。

我假设你有一些删除临时文件夹中所有附件的方法。