2
votes

I have several PST files open in my Outlook and I need to list all the mails within these PST in Excel.

My code lists the mails within my Inbox, and I can't find how to search within all the opened PST.

Here is the structure of my Outlook:

  • Inbox

    • Draft
    • Deleted items
    • Junk emails
    • etc.
  • Budget

  • Stock
  • Country
  • Old
  • etc.

I need to search within the other folders (Budget, Stock, Country...).

Here is my code:

Sub List_mails()

Dim olapp As New Outlook.Application
Dim ns As Object, Dossier As Object
Dim OlExp As Object
Dim i As Object
Dim mybody() As String
Dim fromsender As String

Set ns = olapp.GetNamespace("MAPI")
Set Dossier = ns.GetDefaultFolder(olFolderInbox)
b = 2
For Each i In Dossier.Items
    Cells(b, 1) = i.Subject
    Cells(b, 2) = i.ReceivedTime
    Cells(b, 3) = i.SenderEmailAddress
    b = b + 1
Next i
End Sub
2

2 Answers

1
votes

The easiest way would be to loop over all folders in the namespace like so

For Each f In ns.Folders
    MsgBox (f.Name) '// for testing that you get all folders
Next f

And then reuse your code that you used for the default folder

0
votes

You use .GetDefaultFolder as the method suggest.
To get specific folder other than the default, then use .Folders.

Set Dossier = ns.Folders("Budget")

If you have sub-folders in those folders, then you can use something like:

Dim sDossier As Outlook.Folder
Dim Dossier As Outlook.Folder

Set Dossier = ns.Folders("Budget")

For Each sDossier In Dossier
    '/* put your loop here for items */
Next