Log in

View Full Version : Won't loop though Email Items



tbaker818
03-28-2013, 12:11 PM
I have the following VBA code that won't loop. It does what it's supposed to do, but only for the first item. I checked the count property of fldrFolder.Items and it shows several there:
(why do the VBA tags put all of my code on one line?)

Dim appOutlook As New Outlook.Application
Dim nsMAPI As Outlook.Namespace
Dim fldrInbox As Outlook.Folder
Dim fldrFolder As Outlook.Folder
Dim miEmail As Outlook.MailItem
Set nsMAPI = appOutlook.GetNamespace("MAPI")
Set fldrInbox = nsMAPI.GetDefaultFolder(olFolderInbox)
Set fldrFolder = fldrInbox.Folders("LEAP Updates")
For Each miEmail In fldrFolder.Items
miEmail.Delete
Next miEmail

skatonni
03-28-2013, 04:36 PM
Use this type of loop when moving or deleting.

For I = fldrFolder.Items.Count To 1 Step -1
fldrFolder.Items(I).Delete
Next I

tbaker818
03-28-2013, 08:58 PM
OK, thanks. I figured I'd just end up doing it that way, but wondered what the deal was with the For Each.

Paul_Hossler
03-30-2013, 06:05 AM
OK, thanks. I figured I'd just end up doing it that way, but wondered what the deal was with the For Each.


In a nutshell

Once the For Each deletes (1), what had been (2) is the new (1) and what had been (3) is the new (2)

The For Each thinks it's already looped (1) so now it will delete the (2), which is really the original (3)

This leaves the new (1) which have been the original (2) in the collection.

Back to front the way skatinni used is most common way to delete (including Excel rows BTW), but I have seen



Do While COLL.Count >1
COLL(1).Delete
Loop


Paul

tbaker818
03-30-2013, 04:09 PM
Thank you! :thumb