Looping through Mailitems in MAPI.Items fails to scan all mailitems

  • Thread starter Thread starter Mr. Smith
  • Start date Start date
M

Mr. Smith

Using the following code results in the 'For' loop only
executing twice when 3 emails are present in the Inbox
which moves the emails to another folder.

The "Debug.Print OLFolder.Items.Count" outputs '3'

A subsequent execution of the code DOES identify the
remaining email and moves it as expected.

I am guessing that I must have to refresh some sort of
index PRIOR to the execution of the loop but I have no
idea what that might be. Maybe a particular sort order
is necessary?

Regs
Mr. Smith


Dim OLApp As Object
Dim OLNameSpace As NameSpace
Dim OLInbox As Outlook.Items
Dim OLFolder As Outlook.MAPIFolder
Dim OLToFolder As Outlook.MAPIFolder
Dim OLItem As Outlook.MailItem
Dim i As Integer

Set OLApp = CreateObject("Outlook.Application")
Set OLNameSpace = OLApp.GetNameSpace("MAPI")
Set OLInbox = OLNameSpace.GetDefaultFolder
(olFolderInbox).Items
Set OLFolder = OLNameSpace.Folders("Personal
Folders").Folders("Inbox")
Set OLToFolder = OLNameSpace.Folders("Personal
Folders").Folders(strMoveTo)

Debug.Print OLFolder.Items.Count

For Each OLItem In OLFolder.Items

Debug.Print OLItem.Subject, OLItem.ReceivedTime,
OLItem.Body

OLItem.Move OLToFolder
'If OLItem.Subject Like "*" Then

'Else
' Debug.Print "Not a Bid"
'End If
Next

Exit_SaveAttachment:
Set OLItem = Nothing
Set OLInbox = Nothing
Set OLNameSpace = Nothing
Set OLApp = Nothing
Set OLFolder = Nothing
Set OLToFolder = Nothing
 
Never use Move or Delete inside a For Each ... Next loop, because that resets the index. Instead, you can use a countdown loop:

intCount = OLFolder.Items.Count
For i = intCount to 1 Step - 1
Set OLItem = OLFolder.Items(i)
' your code to work with OLItem
Next

--
Sue Mosher, Outlook MVP
Outlook and Exchange solutions at http://www.slipstick.com
Author of
Microsoft Outlook Programming: Jumpstart
for Administrators, Power Users, and Developers
 
Thanks Sue,

I think I've seen your name a few times helping me out in
these NG's. Appreciated.

Mr. Smith


-----Original Message-----
Never use Move or Delete inside a For Each ... Next
loop, because that resets the index. Instead, you can use
a countdown loop:
 
Back
Top