0

Below code is to save email attachment to a local folder. The trigger is by outlook rules. However, occasionally there will be “An unexpected error has occurred.” from Rules in Error and the code will not work as expected. The file name is standardised and will be sent daily as csv only. File name eg: Report0311.csv

Code that I’ve tried:

Sub SaveAttachmentsToFolder(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = “C:\Users\Me\Home\SaveFolder\”
For Each objAtt In itm.Attachments
obiAtt.SaveAsFile saveFolder & “\” & objAtt.DisplayName
Next
End Sub
8
  • Look closely at your double quotes.... one of them is a "curly/fancy quote" - change it to a normal double quote like the rest and see if that helps.
    – braX
    Commented Jun 6 at 2:04
  • Thanks for helping out. It’s a honest mistake of typo, doubt that is the reason why it failed infrequently. Commented Jun 6 at 2:08
  • Does objAtt.DisplayName have any illegal characters in it when you get the error? There are some characters that cannot be used in a filename.
    – braX
    Commented Jun 6 at 2:14
  • The file name is standardised. Eg: Report0311.csv Commented Jun 6 at 2:26
  • Is Report0311.csv what it actually is when you get the error? Or is that what you think it's supposed to always be? In order to see the actual value, you need to click debug when you get the error and check your variables while it is paused.
    – braX
    Commented Jun 6 at 2:37

1 Answer 1

0

Your code is not checking the attachment type - check if you have a regular by-value attachment (objAtt.Type = olAttachByValue). If you get an embedded message attachment, you can end up with characters illegal in a filename (e.g., ":").

It is a good idea to sanitize the attachment name (use FileName, not DisplayName property) regardless.

3
  • Thanks for the response. Attachment file type will always be csv file with standardise name. Commented Jun 6 at 4:29
  • 1
    Since your code fires on each and every message received, how can you guarantee what the attachment will be every time? Commented Jun 6 at 6:30
  • 1
    I have set up a rule in Outlook to only save attachment from specific subject. The file type for this specific subject will always be csv file. Commented Jun 6 at 7:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.