Get Default Folder Items Collection

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.

Related Articles:

About JP

I'm just an average guy who writes VBA code for a living. This is my personal blog. Excel and Outlook are my thing, with a sprinkle of Access and Word here and there. Follow this space to learn more about VBA. Keep Reading »

Share This Article:

Share and bookmark this articledelicious buttonfacebook buttonlinkedin buttonstumbleupon buttontwitter button
Comments on this article are closed. Why?

Site last updated: February 12, 2012