Search code examples
excelvbaoutlook

Download either all the attachments or the latest in Outlook using VBA Excel


I have been receiving an error:

Run-time error '-2147221233 (8004010f)';
The attempted operation failed. An Object could not be found.

In this line of code

Set objFolder = objNamespace.Folders("Inbox").Folders(strFolderName)

I am trying to download all the attached file from the folder to my specified path.

Here is my code:

Sub OLDownloader()
    
    Dim objOutlook  As Outlook.Application
    Dim objNamespace As Outlook.Namespace
    Dim objFolder   As Outlook.Folder
    Dim objItem     As Object
    Dim objAttachment As Outlook.Attachment
    Dim strFolderName As String
    Dim strSaveFolder As String
    Dim Answer      As String
    
    Set objOutlook = Outlook.Application
    Set objNamespace = objOutlook.GetNamespace("MAPI")
    strFolderName = "Specials"
    strSaveFolder = "C:\Users\Folder"
    
    Set objFolder = objNamespace.Folders("Inbox").Folders(strFolderName)
    
    Answer = MsgBox("Do you want to download the latest file?", vbYesNo, "Downloader")
    
    If Answer = vbYes Then
        Set objItem = objFolder.Items.GetLast
        
        For Each objAttachment In objItem.Attachments
            ' Save the attachment to the specified folder
            objAttachment.SaveAsFile strSaveFolder & objAttachment.Filename
        Next objAttachment
    Else
        For Each objItem In objFolder.Items
            For Each objAttachment In objItem.Attachments
                ' Save the attachment to the specified folder
                objAttachment.SaveAsFile strSaveFolder & objAttachment.Filename
            Next objAttachment
        Next objItem
    End If
    
End Sub

I have tried renaming the folder in my outlook, created new folder for this.
Changed strings into variables.


Solution

  • Instead of using the following line of code:

    Set objFolder = objNamespace.Folders("Inbox").Folders(strFolderName) 
    

    To get any standard folder in Outlook like Inbox you need to use the GetDefaultFolder method of the Namespace class:

    objNamespace.GetDefaultFolder(olFolderInbox).Folders(strFolderName)
    

    Note, any subfolder may not exists, so I'd recommend iterating over all subfolders and checking the Name property to make sure it exists. If the folder doesn't exists you may consider creating it by using Folders.Add method.

    Also I've noticed the following lines of code where you iterate over all items in the folder and try to save attached files if any:

    For Each objItem In objFolder.Items
                For Each objAttachment In objItem.Attachments
    

    Instead, you need to use the Find/FindNext or Restrict methods of the Items class to get only items that have attached files, so you don't have to iterate over all items in the folder.