Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outlook VBA How to loop through inbox and list from email email address if subject matches

Tags:

vba

outlook

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?

like image 683
Superdooperhero Avatar asked Jun 20 '14 07:06

Superdooperhero


1 Answers

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
like image 144
L42 Avatar answered Nov 13 '22 09:11

L42