Move message skips messages when looping through mailbox

J

John_Ba

I'm trying to loop through a mailbox and display a form that chooses whether
to move the message to a different folder and which one to move it to.
For testing I have 2 messages in the mailbox. The problem is that if I choose
to move the firts message then the loop ignores the second message, however
if I don't move the first message then the second message is displayed.
If I run in debug mode with a breakpoint then the code works as expected.
Anybody have a good idea?

Set myOlApp = CreateObject("Outlook.Application")
Set myNameSpace = myOlApp.GetNamespace("MAPI")
Set myMailbox = myNameSpace.folders("Mailbox - RSP SWE DMSII Support")
Set myInbox = myMailbox.folders("Inbox")
'
Set AgentRS = OpenRS(myConn, "SELECT * FROM AgentsColleagues('" & USERCK
& "') ORDER BY Name")
Set AgentForm = New GetAgent
AgentForm.SetAgentList = AgentRS
AgentForm.SetFolderList = myMailbox
'
For Each myItem In myInbox.Items
myItem.Display
' Debug.Print myItem.UserProperties("Owned by")
AgentForm.Init = -1
AgentForm.Show

If AgentForm.AgentList.ListIndex > 0 Then
Set Owner = myItem.UserProperties.Add("Owned by", olText, True)
Owner.Value = AgentForm.AgentList
End If

Set Action = myItem.UserProperties.Add("Action", olText, True)
Action.Value = "NEW"

If AgentForm.FolderList.ListIndex > 0 Then
destFolder = AgentForm.FolderList.List(AgentForm.FolderList.
ListIndex)
myItem.Move (myMailbox.folders(destFolder))
Else
myItem.Close olSave
End If
DoEvents
Next myItem
CloseRS AgentRS

Unload AgentForm
Set AgentForm = Nothing
 
K

Ken Slovak - [MVP - Outlook]

When you are removing items from a collection never use For Each or count up
For loops since you are relying on an index that you are altering as you
remove the items. Use a count down For loop or a Do loop instead:

For i = myInbox.Items.Count To 1 Step -1
myItem = myInbox.Items(i)
' etc.
 
J

John_Ba via OfficeKB.com

Ken,
Thanks very much, that was very helpfull. Pity it doesn't occur in more
programming examples of looping through items. I searched the web and MSDN
looking for a way to do this.
When you are removing items from a collection never use For Each or count up
For loops since you are relying on an index that you are altering as you
remove the items. Use a count down For loop or a Do loop instead:

For i = myInbox.Items.Count To 1 Step -1
myItem = myInbox.Items(i)
' etc.
I'm trying to loop through a mailbox and display a form that chooses
whether
[quoted text clipped - 46 lines]
Unload AgentForm
Set AgentForm = Nothing
 

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