Move items to a specified subfolder inside Outlook based on ReceivedTime

前端 未结 2 1906
情深已故
情深已故 2020-12-12 04:11

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

2条回答
  •  天涯浪人
    2020-12-12 04:18

    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:

    • How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
    • How To: Use Restrict method to retrieve Outlook mail items from a folder

    Then you can use the Move method of the MailItem class to move a Microsoft Outlook item to a new folder. For example:

    Sub MoveItems() 
     Dim myNameSpace As Outlook.NameSpace 
     Dim myInbox As Outlook.Folder 
     Dim myDestFolder As Outlook.Folder 
     Dim myItems As Outlook.Items 
     Dim myItem As Object 
     Dim searchCriteria As String
    
     Set myNameSpace = Application.GetNamespace("MAPI") 
     Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox) 
     Set myItems = myInbox.Items 
     Set myDestFolder = myInbox.Folders("Personal Mail") 
     Set searchCriteria = "[ReceivedTime] >= '" & CStr(Date - 1) & " 06:00PM' AND [ReceivedTime] < '" & CStr(Date) & " 05:30AM'"
     Set myItem = myItems.Find(searchCriteria) 
     While TypeName(myItem) <> "Nothing" 
      myItem.Move myDestFolder 
      Set myItem = myItems.FindNext 
     Wend 
    End Sub
    

    You may find the Getting Started with VBA in Outlook 2010 article helpful.

提交回复
热议问题