ZZA
ZZA

Reputation: 129

Error 13 in for each vba outlook

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

Upvotes: 0

Views: 161

Answers (1)

Kapol
Kapol

Reputation: 6463

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.

Upvotes: 1

Related Questions