outlook-vba Introduction Part 3: Stores and all their folders 3.3 Referencing any folder within any accessible store


Example

TestFldrChain() demonstrates how to reference any folder within any accessible store:

Sub TestFldrChain()

  Dim Fldr As Folder

  Set Fldr = Session.Folders("A").Folders("A2"). _
                           Folders("A21").Folders("A213")

  Debug.Print Join(GetFldrNames(Fldr), "|")

End Sub    

In TestFldrChain(): A is the name of a store; A2 is the name of a folder within A; A21 is the name of a folder within A2 and A213 is the name of a folder within A21.

What is happening here?

Session has a property Folders which is a list of all accessible stores.

Session.Folders(integer), which I used in Part 2 of this tutorial, allows me to step through the stores in sequence when I do not know their names. Session.Folders("A") allows me to access a folder when I know its name.

Session.Folders("A") is a folder and it too has a property Folders.

Session.Folders("A").Folders("A2") gives me access to folder “A2” within store “A”.

I can chain as many Folders("x")s as necessary to reach any folder. If the chain is too long for one line, you can split the statement across several lines as I have.

Look for the most deeply nested folder within your installation and replace A, A2, A21 and A213 by the names of your store and folders. Increase or decrease the number of Folders in the chain as necessary.

If you update and run TestFldrChain(), it will output the following except that A, A2 and so on will have been replaced by your folder names:

A|A2|A21|A213