0

I want to save all attachments from my Outlook 365 inbox.

Copying this tutorial I wrote:

Sub Download_Attachments()

    Dim ns As NameSpace
    Dim olFolder_Inbox As Folder
    Dim olMail As MailItem
    Dim olAttachment As Attachment

    Dim fso As Object
    Dim File_Saved_Folder As String

    File_Saved_Folder_Path = "C:\GIS\temp\mails"

    Set ns = GetNamespace("MAPI")
    
    Set olFolder_Inbox = ns.GetDefaultFolder(olFolderInbox)
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    For Each olMail In olFolder_Inbox.Items
    
        If TypeName(olMail) = "MailItem" And olMail.Attachments.Count > 0 Then
        
            fso.CreateFolder (fso.BuildPath(File_Saved_Folder_Path, Trim(olMail.Subject)))
            
            For Each olAttachment In olMail.Attachments
            
                olAttachment.SaveAsFile fso.BuildPath(File_Saved_Folder_Path, Trim(olMail.Subject)) & "\" & olAttachment.FileName
                                    
            Next olAttachment
        
        End If

    Next olMail
    
    Set olFolder_Inbox = Nothing
    Set ns = Nothing
    
    Set fso = Nothing
    
End Sub

When I execute the macro I get roughly (translated from Swedish):

Error 76, Cant find the path

Community
  • 1
  • 1
BERA
  • 1,345
  • 3
  • 16
  • 36
  • I'm assuiming you're getting the error at line fso.CreateFolder (fso.BuildPath(File_Saved_Folder_Path, Trim(olMail.Subject)))? If so, make sure your subject does not contain [special characters](https://stackoverflow.com/questions/24356993/removing-special-characters-vba-excel) (since files cannot have them). Also limit your subject just in case so you don't create a path too big in naming – Sgdva Aug 10 '22 at 13:58

1 Answers1

0

The Subject property of the MailItem class and the FileName property of the Attachment class may contain forbidden symbols that can't be used for filenames. So. before calling the SaveAsFile method of the Attachment class you need to check the file path whether such folder exists and the path doesn't contain forbidden symbols. See What characters are forbidden in Windows and Linux directory names? for more information.

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