I'm trying to move Outlook Items, However the code runs with no error messages but no emails are moved.
This leads me to belief the necessary IF condition
is never being met? However I could be wrong.
Please find code below.
Sub Gatekeeper()
Dim aItem As Object
Dim mail As Object
Dim strTime As String
Dim Items As Outlook.Items
Dim olNs As Outlook.NameSpace
Dim subfolder As Outlook.MAPIFolder
Set olNs = Application.GetNamespace("MAPI")
Set mail = olNs.GetDefaultFolder(olFolderInbox)
Set Items = mail.Items
For Each aItem In Items
strTime = aItem.ReceivedTime
If strTime > #6:00:00 PM# And strTime < #5:30:00 AM# Then
Set subfolder = mail.Folders("Nights")
aItem.Move subfolder
End If
Next aItem
End Sub
You shouldn't use For Each...Next Loop when you are Moving /deleting or modifying collection Items
Work with For...Next Statement - Down for loop:
Also remember there are objects other than MailItem in your Inbox so check If Items.Class = olMail Then or you will encounter and error on your loop
You may also wanna use Items.Restrict Method (Outlook) to improve your loop
Code Example
Make sure to set your Filter correctly, I'm assuming your looking at yesterdays
06:00PM
CStr(Date - 1) = (today - 1 day)CStr and Date
Instead of iterating over all items in the folder you need to find items that correspond to your conditions and move them to a subfolder (or any other folder) by calling the Move method.
You need to use the Find/FindNext or Restrict methods of the
Items
class to find all items that correspond to your conditions (read and sender name). Read more about these methods in the following articles:Then you can use the Move method of the MailItem class to move a Microsoft Outlook item to a new folder. For example:
You may find the Getting Started with VBA in Outlook 2010 article helpful.