0

I want to delete a mail when the delivered response comes. This is a fragment of my code. I don't understand why the for each runs into error 13

Sub test222()

Dim oapp As Outlook.Application
Dim osession As Outlook.NameSpace
Dim oInbox As Outlook.MAPIFolder
Dim oSentItem As Outlook.MAPIFolder

Dim omail As Outlook.MailItem
Dim conID As String

Set oapp = New Outlook.Application
Set osession = oapp.GetNamespace("MAPI")
Set oInbox = osession.GetDefaultFolder(olFolderInbox)
Set oSentItem = osession.GetDefaultFolder(olFolderSentMail)

i = 1
For Each omail In oSentItem.Items

If (omail.Subject = "Delivered: aa") Then
     Msgbox "Hi"
     omail.Delete

     Exit For
              Else
     i = i + 1
     End If         
Next

End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ZZA
  • 129
  • 1
  • 11

1 Answers1

1

Declare omail as Object and check TypeName in the loop. The way you did it, there will be a type mismatch error when the loop runs into something else than an e-mail message, e.g. an appointment item.

Also read about late binding. I'd advise to use this functionality when you are working with non-default libraries.

Kapol
  • 6,383
  • 3
  • 21
  • 46
  • Tested it, but ran into some other problems. This doesn't work on delivery receipts, only works for one time only: when I test it with some subjects, I get the msgbox, but the mail won't get deleted. When I run the macro again, nothing happens. **However the main problem is, that it doesn't work on delivered reciepts.** – ZZA Feb 20 '14 at 09:57
  • I can't reproduce the problem you're running into, but I suggest checking what type the delivery receipt has. Is it a MailItem? – Kapol Feb 20 '14 at 10:21
  • It is supposed to be a ReportItem it seems. I have tried this code [link]http://stackoverflow.com/questions/78924/when-is-a-mailitem-not-a-mailitem , but modified with: `If TypeName(msg) = ReportItem Then MsgBox "2"` in the for cycle, but it doesnt do anything. – ZZA Feb 20 '14 at 10:53
  • 1
    TypeName returns a string. – Kapol Feb 20 '14 at 11:47