My goal is to move all emails that are unread and not flagged from inbox to the inbox folder of a local .pst see the attached. I have not been able to figure out when to start.
I could not find a case where this has been doe before. AI-generated code could not compile, and I sadly am not familiar with using .vba in outlook.
There are several tasks that must be completed for that. The very first one is to find the required items that correspond to the specified search criteria. To get that part done you need to use the Find
/FindNext
or Restrict
methods of the Items
class. Read more about these methods in the articles that I wrote more than a decade ago for the technical blog:
But if you need to process multiple folders at once you would better consider the AdvancedSearch
method of the Outlook Application
class. The key benefits of using the AdvancedSearch
method in Outlook are:
AdvancedSearch
method runs it automatically in the background.Restrict
and Find
/FindNext
methods can be applied to a particular Items
collection (see the Items
property of the Folder
class in Outlook).IsInstantSearchEnabled
property of the Store
class).Stop
method of the Search
class.See Advanced search in Outlook programmatically: C#, VB.NET for more information.
The next thing is to move found items to the required folder. The Move method moves 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
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set myDestFolder = myInbox.Folders("Personal Mail")
Set myItem = myItems.Find("[UnRead] = true")
While TypeName(myItem) <> "Nothing"
myItem.Move myDestFolder
Set myItem = myItems.FindNext
Wend
End Sub
But in your scenario you need to get a folder from another store/account:
Sub EnumerateStores()
Dim colStores As Outlook.Stores
Dim oStore As Outlook.Store
Dim oRoot As Outlook.Folder
On Error Resume Next
Set colStores = Application.Session.Stores
For Each oStore In colStores
Set oRoot = oStore.GetRootFolder
Debug.Print (oRoot.FolderPath)
Next
End Sub