PDA

View Full Version : Macro skips emails it is supposed to delete



musicgold
02-02-2012, 10:28 AM
Hi,


I use the following code to clean my Outlook inbox. However, I have noticed that sometimes it doesn’t delete all the emails it should delete in the first sweep. It however deletes them in the second or third sweep. Why does it happen?




Dim oloutlook As Outlook.Application
Dim ns As Outlook.NameSpace
Dim itm As Object
Dim Myitem As MailItem
Dim counter As Integer
Dim olTrash As Object

Set oloutlook = CreateObject("Outlook.Application")
Set ns = oloutlook.GetNamespace("MAPI")
Set itm = ns.GetDefaultFolder(olFolderInbox)
Set olTrash = ns.GetDefaultFolder(olFolderDeletedItems)


For Each MyItem In itm.Items

Select Case UCase(MyItem.SenderName)

Case UCase("ABCD")
MyItem.Move olTrash
counter = counter + 1

Case UCase("EFGH")
MyItem.Move olTrash
counter = counter + 1

End Select

Next

JP2112
02-23-2012, 01:56 PM
You need to loop backwards when deleting or moving emails, because doing so changes the loop counter.

Instead of

For Each MyItem In itm.Items


You would need


For i = itm.Items.Count To 1 Step -1


and use itm.Items(i) to refer to the current email in the loop.