For Each loop not deleting all items

心已入冬 提交于 2020-06-28 07:10:12

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/19137409/for-each-loop-not-deleting-all-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!