0

I have some code that imports emails into a form. However, it gets caught up on calender invites an such. As a response, I would like to filter out all these calender invites so they are not even trying to import in the first place. This is the code i have so far:

    Dim SenderCheck As String
'Build the list selection box
j = 0
For i = 1 To Emails.Count
    With ListBox_Emails
    If TypeName(Item) = "MailItem" Then
    SenderCheck = Emails(i).Sender.Address
    If InStr(1, SenderCheck, "express-scripts.com") > 0 Then
        .AddItem Emails(i).Sender
        .List(j, 1) = Emails(i).Subject
        .List(j, 2) = Emails(i).ReceivedTime
        .List(j, 3) = "N"
        j = j + 1
        Else: MsgBox "error"
        End If
    Else: MsgBox "not mail item"
    End If
            End With
    On Error GoTo TEMP

The issue is with the line If TypeName(Item)="MailItem" then as everything is now deemed not a mail item and I get the "Not a mail item" error.

How would I go about fixing this issue? I think the syntax is incorrect but I can not figure out how to correct it.

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
tokyo_north
  • 115
  • 1
  • 9
  • Perhaps unrelated to your main question, but did you mean to tag this question as "excel" and not "outlook"? Also, what is `Item`? You are using `Emails(i)` everywhere else in the loop. – BigBen Jun 26 '19 at 16:58
  • @BigBen yes this is within an excel file. Also, that was just a recent typo. Even with `Emails(i)` in there it doesn't filter correctly. – tokyo_north Jun 26 '19 at 17:20
  • Can you share the rest of your code, for better context? – BigBen Jun 26 '19 at 17:36
  • Use olMail Class - Example https://stackoverflow.com/a/42547062/4539709 or Value 43, [sid](https://stackoverflow.com/a/56778847/4539709) answer should work. – 0m3r Jun 26 '19 at 19:43

1 Answers1

1

This works just fine for me. It skips the calendar invites

Option Explicit

Sub Sample()
    Dim OutApp As Object
    Dim oMail As Object, Item As Object
    Dim objNS As Object, olFolder As Object

    Set OutApp = CreateObject("Outlook.Application")
    Set objNS = OutApp.GetNamespace("MAPI")
    Set olFolder = objNS.GetDefaultFolder(6) '<~~ olFolderInbox = 6

    For Each Item In olFolder.Items
        'https://learn.microsoft.com/en-us/office/vba/api/outlook.olobjectclass
        If Item.Class = 43 Then
            Set oMail = Item
            Debug.Print oMail.Subject
            Debug.Print oMail.SenderEmailAddress
        End If
    Next
End Sub
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250