Consider the following Outlook VBA code:
Sub Macro1() 'Move e-mail messages from "Inbox" folder to "New Applications"
Dim olMapi As NameSpace
Dim olStore As Outlook.Store
Dim olRootFldr As Outlook.Folder
Dim olFldrInbox As Outlook.Folder
Dim olFldrSbmtd As Outlook.Folder
Dim dateMin As Date, dateMax As Date
Dim sFilterDmin As String
Dim sFilterDmax As String
Dim olItm As Object
Dim olEmls As Outlook.Items
Dim olEml As Outlook.MailItem
Dim nApplications as Integer
Set olMapi = Application.GetNamespace("MAPI")
Set olStore = olMapi.Stores("Application Processing Department")
Set olRootFldr = olStore.GetRootFolder
Set olFldrInbox = olRootFldr.Folders("Inbox")
Set olFldrSbmtd = olRootFldr.Folders("Submitted Applications")
dateMax = Date - 5
dateMin = dateMax - 2
sFilterDmin = "[ReceivedTime]>='" & Format(dateMin, "DDDDD HH:NN") & "'"
sFilterDmax = "[ReceivedTime]<='" & Format(dateMax, "DDDDD HH:NN") & "'"
Set olEmls = olFldrInbox.Items.Restrict(sFilterDmin)
If olEmls Is Nothing Then MsgBox "!olEmls1": Exit Sub
Set olEmls = olEmls.Restrict(sFilterDmax)
If olEmls Is Nothing Then MsgBox "!olEmls2": Exit Sub
'MsgBox "olEmls.Count=" & olEmls.Count
nApplications = 0
For Each olItm In olEmls
If TypeOf olItm Is Outlook.MailItem Then
Set olEml = olItm
If Not olEml Is Nothing Then
If Left(UCase(olEml.Subject), 16) = "APPLICATION FOR " Then
olEml.Move olFldrSbmtd.Folders("New Applications")
nApplications = nApplications + 1
End If
Set olEml = Nothing
End If
End If
DoEvents
Next olItm
MsgBox "moved nApplications=" & nApplications
End Sub
When I have one message in the Inbox with Subject that starts with “New Application for …” then MsgBox shows “moved nApplications=1” and that message gets moved to the “New Applications” folder as expected.
If there are two messages then MsgBox still shows “moved nApplications=1” and I have to run this macro again to move the second message.
What should be changed in my code above to force Items.Restrict() method to include both/all messages satisfying the given criteria? Btw, if there are 10 messages in the Inbox then the first run of macro may show “moved nApplications=3” (sometimes “moved nApplications=4”); second invocation may show “moved nApplications=2”, but it never shows the expected result.
That is because you are using a For Each
loop and you are changing the collection that you are iterating over. Use a down for
loop
for i= olEmls.Count to 1 step -1
set olItm = olEmls(i)
1