views:

164

answers:

2

I have the following macro in outlook to clear my deleted folder. its strange as it doesn't seem to delete all entries. I have to run this a few times for it to clear to deleted items folder. (usually 2 or 3 times). Each time the number of deleted items in the folder does get reduced but i dont understand why everything doesn't get wiped out in the first go. anything wrong with this code below ?

Public Sub EmptyDeletedEmailFolder()

Dim outApp As Outlook.Application
Dim deletedFolder As Outlook.MAPIFolder
Dim item As Object
Dim entryID As String

Set outApp = CreateObject("outlook.application")
Set deletedFolder = outApp.GetNamespace("MAPI").GetDefaultFolder(olFolderDeletedItems)

For Each item In deletedFolder.Items
    item.Delete             ' Delete from mail folder
Next

Set item = Nothing
Set deletedFolder  = Nothing
Set outApp = Nothing

End Sub

+2  A: 

Try:

For i = deletedFolder.Items.Count To 1 Step -1
    deletedFolder.Items(i).Delete             '' Delete from mail folder
Next

There can be problems with deleting items from a collection.

Remou
this kinda worked but there is a bug in it. i will edit your answer with the fix . .
ooo
the latest post now works . . .
ooo
Thanks :) char, char
Remou
A: 

By deleting the objects in the collection "underneath" the iterator, it couldn't really go over each item in the collection because the collection was changing. Remou came up with a really good way that will be guaranteed to continuously delete items in the collection as long as there are items left. Just don't be deleting items yourself while the method runs or you could run into prolems.

Knobloch