Search code examples
vbaoutlookoutlook-filter

Move specific mails from one folder to another


in Outlook I would like to have a FollowUp-Solution that checks a specific folder (Source Folder) if there are mails older than 1 days and moves them in another specific folder (Target Folder).

My problem is that it seems as my code isn't looping the SourceFolder properly. Some mails are moved but some old mails are still in the SourceFolder.

When I restart the Code some of the remaining mails are moved now but still some remain in the SourceFolder.

I tried to loop the Items in other ways (with; for each; do) but I guess my vba understanding is too bad to get a working solution.

Sub MoveFollowUpItems()
Dim FolderTarget    As Folder
Dim FolderSource    As Folder
Dim Item            As Object
Dim FolderItems     As Outlook.Items

Set FolderTarget = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set FolderSource = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders("FollowUp")

Set FolderItems = FolderSource.Items

For Each Item In FolderItems
    If Item.ReceivedTime < Date - 1 Then    '
        Item.Move FolderTarget
        End If
    Next
End Sub

Does anyone know how to handle the propper looping?


Solution

  • For Each Loop is a great but When moving/deleting items Loop Through in Reverse Order you know count down (ie 3,2,1). In order to do this, you can incorporate Step -1 into your loop statement.

    Also to improve your loop try using Items.Restrict Method (Outlook) on your date filter

    Example

    Option Explicit
    Sub MoveFollowUpItems()
        Dim FolderTarget    As Folder
        Dim FolderSource    As Folder
        Dim FolderItems     As Outlook.Items
    
        Set FolderTarget = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
        Set FolderSource = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders("FollowUp")
    
        Dim Filter As String
            Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:datereceived" & _
                              Chr(34) & " <= 'Date - 1' "
    
        Set FolderItems = FolderSource.Items.Restrict(Filter)
    
        Debug.Print FolderItems.Count
    
        Dim i As Long
        For i = FolderItems.Count To 1 Step -1
            Debug.Print FolderItems(i) 'Immediate Window
    '        FolderItems(i).Move FolderTarget
        Next
    
    End Sub