Safinn
Safinn

Reputation: 632

For Each loop not deleting all items

I have a macro which is supposed to delete emails over 'x' amount of days old when I quit Outlook 2007 but it only seems to delete a few of them and when I open it and quit again it deleted the rest. Here is the code:

Private Sub Application_Quit()

Dim myOlApp, myNameSpace As Object
Dim MyItem As Object
Dim DeletedFolder As Object

Set myOlApp = CreateObject("Outlook.Application")
Set myNameSpace = myOlApp.GetNamespace("MAPI")
'Set DeletedFolder = myNameSpace.GetDefaultFolder(olFolderDeletedItems)
Set DeletedFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Auto")

For Each MyItem In DeletedFolder.Items
If DateDiff("d", MyItem.ReceivedTime, Now) > 7 Then
MyItem.Delete
End If
Next

End Sub

In this example I chose greater than 7 days old in the Auto folder under my Inbox folder. Any ideas why it does not delete them all the first time?

Thanks

Upvotes: 1

Views: 223

Answers (1)

David Zemens
David Zemens

Reputation: 53623

Generally when deleting you need a different sort of iteration:

Dim m as Long
For m = DeletedFolder.Items.Count to 1 Step -1
    Set myItem = DeletedFolder.Items(m)
    If DateDiff("d", MyItem.ReceivedTime, Now) > 7 Then
        MyItem.Delete
    End If
Next

This is because, as you delete an element from the collection, the collection is re-indexed. So you need to step backwards through the collection, otherwise you will "skip" some items.

Upvotes: 2

Related Questions