0

I would like to ask for help. I am using Office 365 and tried to use this code to save attachments from Outlook and rename them as subject of email. However I encountered the problem.

This VBA code is working:

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\Users\ppp\Desktop\Image Test"

For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "" & objAtt.DisplayName


Set objAtt = Nothing
Next
End Sub

However when I want to amend it so that it saves the pdf attachments with the subject of the email it is not working. File is being saved down as type: file (not PDF) and size is 0 KB. Additionaly it doesn't save down the file with the subject name but with the name of the attachment.

VBA code which I am using

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\Users\ppp\Desktop\Image Test"
MSN = Trim(itm.Subject)

For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "" & itm.Subject & ".PDF"

Set objAtt = Nothing
Next 
End Sub

Can somebody advise me please?

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Marek
  • 82
  • 6
  • 2
    You might be missing a slash here: `objAtt.SaveAsFile saveFolder & "\" & itm.Subject & ".PDF"` – Grok42 Jul 25 '23 at 20:02
  • Note that the subject may contain characters which aren't valid in a filename. See here https://www.slipstick.com/developer/saving-messages-to-the-hard-drive-using-vba/#:~:text=Function%20StripIllegalChar(StrInput) for suggestion on "cleaning" the subject – Tim Williams Jul 25 '23 at 20:06
  • Also note you're potentially trying to save multiple attachments with the same name. – Tim Williams Jul 25 '23 at 20:08

1 Answers1

0

First, you need to use unique names for files saved to the disk. In the following code the subject property is used for all attachments:

For Each objAtt In itm.Attachments
  objAtt.SaveAsFile saveFolder & "" & itm.Subject & ".PDF"
  Set objAtt = Nothing
Next 

So, you need to add a unique ID to the file name to be able to have them all on the disk. Otherwise, the same file with the Subject name will be overwritten.

Second, make sure that file name passed to the SaveAsFile method doesn't contain forbidden symbols. See Remove illegal characters while saving workbook Excel VBA for more information.

Third, make sure that you pass a valid file path to the SaveAsFile method. I'd recommend adding the Debug.Print statement which could help to identify possible issues with a file path. Just try to print the result file path string to the console and see whether it was built correctly or not.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45