vbaoutlook

VBA in Outlook doesn't find Inbox messages


I have several messages selected.

I run the following VBA script in Outlook 365:

Sub FindMessages()
    Dim objNS As Outlook.NameSpace
    Dim olFolder As Outlook.MAPIFolder
    
    Set objNS = GetNamespace("MAPI")
    Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
    Debug.Print "Items in Inbox: " & olFolder.Items.Count
    
    Debug.Print "Selected items: " & Application.ActiveExplorer.Selection.Count
    
End Sub

The output is:

Items in Inbox: 0
Selected items: 6

I can't get the messages in Inbox. This will be an automated routine, so I can't manually select the messages.

I tried various formulations of .GetDefaultFolder(olFolderInbox).


Solution

  • This can happen if there are multiple stores in the profile and the Inbox folder from the default message store is not the Inbox folder you have selected in Outlook. Try to change the line

    Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
    

    to

    Set olFolder = Application.ActiveExplorer.CurrentFolder