After adding a new store in Outlook you can find it in the Stores
collection which you may get by using the Stores property of the Namespace class. Use the Stores
and Store
objects to enumerate all folders and search folders on all stores in the current session. The following VBA sample code shows how you can use these objects to iterate over all stores and folders in Outlook:
Sub EnumerateFoldersInStores()
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)
EnumerateFolders oRoot
Next
End Sub
Private Sub EnumerateFolders(ByVal oFolder As Outlook.Folder)
Dim folders As Outlook.folders
Dim Folder As Outlook.Folder
Dim foldercount As Integer
On Error Resume Next
Set folders = oFolder.folders
foldercount = folders.Count
'Check if there are any folders below oFolder
If foldercount Then
For Each Folder In folders
Debug.Print (Folder.FolderPath)
EnumerateFolders Folder
Next
End If
End Sub
Note, the Outlook object model is common for all programming languages, so you may find the sequence of property and methods calls in the sample shown above.
To find items that correspond to your conditions you need to use the Find
/FindNext
or Restrict
methods of the Items
class. In that case you will get only items that correspond to the search criteria and then you can iterate over them only. Read more about these methods in the articles I wrote for the technical blog:
If you need to find items in multiple folders I'd recommend choosing the AdvancedSearch
method of the Application
class instead. The key benefits of using the AdvancedSearch
method in Outlook are:
- The search is performed in another thread. You don’t need to run another thread manually since the
AdvancedSearch
method runs it automatically in the background.
- Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The
Restrict
and Find
/FindNext
methods can be applied to a particular Items
collection (see the Items
property of the Folder
class in Outlook).
- Full support for DASL queries (custom properties can be used for searching too). To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the
IsInstantSearchEnabled
property of the Store
class).
- You can stop the search process at any moment using the
Stop
method of the Search
class.
See Advanced search in Outlook programmatically: C#, VB.NET for more information.