Search code examples
vbaloopsoutlookoutlook-filter

Loop through outlook unread emails not working


I am having trouble getting this loop to work. Any advice?

   Sub SaveEmailAttachmentsToFolder(OutlookFolderInInbox As String, _
                                 ExtString As String, DestFolder As String)
    Dim ns As NameSpace
    Dim Inbox As MAPIFolder
    Dim SubFolder As MAPIFolder
    Dim Item As Object
    Dim Atmt As Attachment
    Dim FileName As String
    Dim MyDocPath As String
    Dim i As Integer
    Dim wsh As Object
    Dim fs As Object
    Dim InboxMsg As Object


    On Error GoTo ThisMacro_err

    Set ns = GetNamespace("MAPI")
    Set Inbox = ns.GetDefaultFolder(olFolderInbox)
    Set SubFolder = Inbox.Folders(OutlookFolderInInbox)



    'To fix my issue I may have to change the loop to repeat the same number of 
    times as attachments

    ' Check subfolder for messages and exit of none found
    '    strFilter = "[Unread] = True"
    '    Set inboxItems = 

  ns.GetDefaultFolder(olFolderInbox).Folders(OutlookFolderInInbox).Items.Restrict(strFilter)


        If SubFolder.UnReadItemCount = 0 Then
        MsgBox "There are no New messages in this folder : " & 
    OutlookFolderInInbox, _
               vbInformation, "Nothing Found"
        Set SubFolder = Nothing
        Set Inbox = Nothing
        Set ns = Nothing
        Exit Sub
    End If

    'Create DestFolder if DestFolder = ""
    If DestFolder = "" Then
        Set wsh = CreateObject("WScript.Shell")
        Set fs = CreateObject("Scripting.FileSystemObject")
        MyDocPath = wsh.SpecialFolders.Item("mydocuments")
        DestFolder = MyDocPath & "\" & Format(Now, "dd-mmm-yyyy hh-mm-ss")
        If Not fs.FolderExists(DestFolder) Then
            fs.CreateFolder DestFolder
        End If
    End If

    If Right(DestFolder, 1) <> "\" Then
        DestFolder = DestFolder & "\"
    End If

    ' Check each message for attachments and extensions
    strFilter = "[Unread] = True"
    Set inboxItems = 

  ns.GetDefaultFolder(olFolderInbox).Folders(OutlookFolderInInbox).Items.Restrict(strFilter)

 '   For Each Item In inboxItems
    For i = inboxItems.Count To 1 Step -1 'Iterates from the end backwards
        Set InboxMsg = Inbox.Items(i)
  'For Each Item In inboxItems
   '      For Each Atmt In inboxItems(I).Attachments
       For Each Atmt In InboxMsg.Attachments

            If LCase(Right(Atmt.FileName, Len(ExtString))) = LCase(ExtString) 
    Then
                FileName = DestFolder & Format(Item.ReceivedTime, "yyyy-mmm-dd") & Atmt.FileName
                Atmt.SaveAsFile FileName

            End If
         Item.UnRead = "False"
    '        inboxItems(I).UnRead = "False"
        Next Atmt
    '         Item.UnRead = "false"

    Next


    ' Show this message when Finished
    If i = 0 Then
        MsgBox "You can find the files here : " _
             & DestFolder, vbInformation, "Finished!"
    Else
        MsgBox "No attached files in your mail.", vbInformation, "Finished!"
    End If

    ' Clear memory
    ThisMacro_exit:
    Set SubFolder = Nothing
    Set Inbox = Nothing
    Set ns = Nothing
    Set fs = Nothing
    Set wsh = Nothing
    Exit Sub

    ' Error information
    ThisMacro_err:
    MsgBox "An unexpected error has occurred." _
         & vbCrLf & "Please note and report the following information." _
         & vbCrLf & "Macro Name: SaveEmailAttachmentsToFolder" _
         & vbCrLf & "Error Number: " & Err.Number _
         & vbCrLf & "Error Description: " & Err.Description _
         , vbCritical, "Error!"
    Resume ThisMacro_exit

    End Sub

Solution

  • Here is Quick example, set filter for both UnRead & Items with Attachments

    Option Explicit
    Public Sub Example()
        Dim olNs As Outlook.NameSpace
        Dim Inbox As Outlook.MAPIFolder
        Dim Items As Outlook.Items
        Dim i As Long
        Dim Filter As String
    
        Set olNs = Application.GetNamespace("MAPI")
        Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    
        Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                           Chr(34) & "=1 AND " & _
                           Chr(34) & "urn:schemas:httpmail:read" & _
                           Chr(34) & "=0"
    
        Set Items = Inbox.Items.Restrict(Filter)
    
        For i = Items.Count To 1 Step -1
            Debug.Print Items(i) 'Immediate Window
        Next
    End Sub