In Outlook, you might have a need to grab the items collection for any of the default folders. For example, if you wanted to iterate through a folder and set flags, create reminders, or move emails based on subject, you'd want a reference to the Items collection for that folder.
I wrote a small utility function that encapsulates this, er, function. I came across the need while writing the code for my next blog post, which will show you how to save all the attachments from the messages a given mail folder to a folder on your hard drive.
Function GetDefaultFolderItems(outlookFolder As OlDefaultFolders) _
As Outlook.Items
' returns Items collection from any default folder
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace
Dim olFldr As Outlook.MAPIFolder
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set olFldr = olNS.GetDefaultFolder(outlookFolder)
Set GetDefaultFolderItems = olFldr.Items
End Function
Usage:
Sub testme() Dim itemsCollection As Outlook.Items itemsCollection = GetDefaultFolderItems(olFolderDeletedItems) End Sub
As you can see above, the parameter for the function is declared as an enumerated constant (OlDefaultFolders). This means that after you type "GetDefaultFolderItems(" Intellisense gives you a list of the built in constants representing the default folder types. Just choose one and your object variable (in my example, itemsCollection) will contain an object reference to the Items collection for the Deleted Items folder.
Now you can do a For Each loop to iterate through the items, or filter them with the Restrict Method, or any other method appropriate for the Items Collection.
Currently it works for the default folders only, but in my next post I'll show you a technique for expanding it to work with any Outlook folder.
Follow Me