3
votes

I am trying to access the sub folder by name "MacroEnabled" in Inbox, find all the attachments in it and save them to local drive.

I use this code to create a folder by name "Documents" and save the attachments. However while doing the second iteration it says file already exist error "58".

    Dim ns As NameSpace
    Dim olFolder_Inbox As Folder
    Dim olMail As MailItem
    Dim olAttachment As Attachment
    Dim FolderPath As String
    Dim fso As Object
    Dim File_Saved As String
    
    'email service type
    Set ns = GetNamespace("MAPI")
    Set olFolder_Inbox = ns.GetDefaultFolder(olFolderInbox).Folders("MacroEnabled")

    Set fso = CreateObject("Scripting.FileSystemObject")
    FolderPath = "Documents"
    For Each olMail In olFolder_Inbox.Items

        If TypeName(olMail) = "MailItem" And olMail.Attachments.Count > 0 Then
            fso.CreateFolder ("Documents")
            
            For Each olAttachment In olMail.Attachments
            
                olAttachment.SaveAsFile fso.BuildPath(FolderPath, olAttachment.FileName)
                
            Next olAttachment

        End If
    
    Next olMail

    Set ns = Nothing
    Set fso = Nothing

End Sub
2
Looks like your code continually tries to recreate the Documents folder? So you probably need to first check if it exists, at least assume it does after the first time you create it. - lurker
And you can use the FolderExists method to do that check. - Andrew Morton
Same thing applies to the attachments if two share the same name. - Tim Williams

2 Answers

1
votes

First of all FolderPath should present whole path eg. FolderPath = "C:\Documents" If you need you can use relative path for example FolderPath = CurrentProject.Path & "\Documents" Then you can use FolderExisits method in loop by adding following instruction:

If Not fso.FolderExists(FolderPath) Then fso.CreateFolder (FolderPath )
0
votes

For Each olMail In olFolder_Inbox.Items fso.CreateFolder ("Documents_path")

look at this and try to check if folder Documents exists before creating another