Deleting Mail Items - Code

N

Nigel RS

The following snippet of VBA code (Outlook 2003) is used to selectively
delete mail items from a selected mail folder. where the mail item subject
matches a predefined string (MailSubject). This code works great except it
fails to delete the last item. If there are 10 items matching it will delete
9 but leave one behind. If there is only 1 it fails to delete it.

If I step the code in the debugger it works! What could be causing this?

For Each objItem In objFolder.Items
' delete the item from the folder
If Left(objItem.Subject, mSubLen) = MailSubject Then
objItem.Delete
End If
Next
 
K

Ken Slovak - [MVP - Outlook]

Don't use For Each loops or up counting For loops for deleting items from a
collection. Use For loops that count down (Step -1) or use Do loops that
test for no items left.
 
N

Nigel RS

Thanks Ken, I guess it is similar to deleting rows in Excel. I will change
it to a down counter.

Cheers
 
N

Nigel RS

Hi Ken
I modified my code as suggested by using a count down structure, however it
still does not delete the last item that meets the criteria !! Stepping
through the code the test is applied and the delete step is run, but the last
mailitem remains in the folder! Any ideas?

For iItem = objFolder.Items.Count To 1 Step -1

Set objItem = objFolder.Items(iItem)

' delete the item from the inbox
If Left(objItem.Subject, mSubLen) = MailSubject Then
objItem.Delete
End If

Next iItem
 
K

Ken Slovak - [MVP - Outlook]

See if adding a DoEvents after you delete the item in the loop helps with
that.
 
K

Ken Slovak - [MVP - Outlook]

Outlook collections always run from 1 to number, not from 0.
 
N

Nigel

Hi Ken
Sorry for delay, I tried adding DoEvents without success.

--

Regards,
Nigel
(e-mail address removed)
 
K

Ken Slovak - [MVP - Outlook]

OK, then you might have to add a test after the loop to see if there's still
any items left in that collection and if so try either getting that last
item as an object item and calling its Delete() method again or using
Items.Remove(1) and see if either of those works.

In some versions of Outlook removing the last item in a collection using
Delete() doesn't work. That might be what you're running into here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top