PDA

View Full Version : Looping through a custom created folder



jackCell
01-29-2018, 06:51 PM
Hi all,

I have searched online but to no avail. I would like outlook to loop through a specific self created folder that I have Created inside a shared mailbox. For example, in outlook, I created a folder called "test" and inside test I have another sub folder called 2017. I would like to access this test folder in which I have created.

Cheers,
jack

gmayor
01-29-2018, 10:27 PM
It rather depends where you have created the folder in relation to the root folder of the account. e.g. assuming that your folder is a sub folder of a folder that is a sub folder of the Inbox, you can loop through all your inbox folders and their sub folders to find the matching name as below, then having found such a folder you can look through the items in it and do something with one or more of them.


Option Explicit

Sub Macro1()
Dim cFolders As Collection
Dim olFolder As Outlook.Folder
Dim SubFolder As Folder
Dim olNS As Outlook.NameSpace
Dim olItem As MailItem
Dim i As Long
On Error Resume Next
Set cFolders = New Collection
Set olNS = GetNamespace("MAPI")
cFolders.Add olNS.GetDefaultFolder(olFolderInbox)
Do While cFolders.Count > 0
Set olFolder = cFolders(1)
cFolders.Remove 1
If olFolder.Name = "2017" Then 'the name of the folder to process
For i = olFolder.Items.Count To 1 Step -1
'process in reverse order if you plan to remove any of the items from the list
Set olItem = olFolder.Items(i)
'do something with the items
Debug.Print olItem.Subject
Next i
Exit Do
End If
For Each SubFolder In olFolder.folders
cFolders.Add SubFolder
Next SubFolder
Loop
lbl_Exit:
Set olFolder = Nothing
Set SubFolder = Nothing
Set olItem = Nothing
Exit Sub
End Sub

If you know the exact path of your sub folder you can access it directly e.g. using the same folder location


Sub Macro2()
Dim olFolder As Outlook.Folder
Dim olNS As Outlook.NameSpace
Dim olItem As MailItem
Dim i As Long
Set olNS = GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(olFolderInbox).folders("Test").folders("2017")
For i = olFolder.Items.Count To 1 Step -1
'process in reverse order if you plan to remove any of the items from the list
Set olItem = olFolder.Items(i)
'do something with the items
Debug.Print olItem.Subject
Next i
lbl_Exit:
Set olFolder = Nothing
Set olItem = Nothing
Exit Sub
End Sub


With this example path both approaches should give the same results.