11

I'm trying to use Outlook VBA to loop through the inbox and list the from email address if the subject matches a string. Got this so far from googling, but it's not working:

Dim objNS As Outlook.NameSpace
Set objNS = GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items

Dim oFolder As Outlook.MAPIFolder
Dim oMail As Outlook.MailItem
For Each oMail In Items
    Debug.Print oMail.SenderEmailAddress
Next

Anybody know why I get a Type Mismatch error when I run this?

Superdooperhero
  • 7,584
  • 19
  • 83
  • 138
  • Which line returns the mismatch? Btw, remember that not all items in the inbox is of type `MailItem`. If that is the case, that will trigger a mismatch error in your `For Each Loop`. – L42 Jun 20 '14 at 08:34

1 Answers1

27

As commented, try incorporating a test for MailItem in your code:

Dim objNS As Outlook.NameSpace: Set objNS = GetNamespace("MAPI")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
Dim Item As Object

For Each Item In olFolder.Items
    If TypeOf Item Is Outlook.MailItem Then 
        Dim oMail As Outlook.MailItem: Set oMail = Item
        Debug.Print oMail.SenderEmailAddress
    End If
Next

Edit1: As suggested by Dmitry, you can also use:

If Item.Class = 43 Then

in place of

If TypeOf Item Is Outlook.MailItem Then
L42
  • 19,427
  • 11
  • 44
  • 68
  • In case someone else is looking for another folder than Inbox you can check the available ones at: https://learn.microsoft.com/en-us/office/vba/api/outlook.oldefaultfolders – RCaetano Aug 25 '23 at 16:30