Hello,
I have an outlook app that creates and sends email for me. In order to keep my inbox from filling up with returned mail, the macro uses the searchobject to find certain strings in the subject line and delete these messages. The macro then uses the search complete event to delete the search results and empty the Sent mail folder and the Deleted Items folder. The problem is, the search seems to miss some items. For example, if I have 10 identical emails in the inbox with "undeliverable" in the subject line, the macro will only delete, say, 4 of them. In addition, the macro does not completely empty the Deleted Items folder, it just deletes a handful of emails each time it is run.

Here is the code. Also, if anybody knows a better way to delete search results or empty a MAPI folder, let me know. Thanks!

Function CleanUpInbox()
'Searches the Inbox for returned mail

Dim objSch As Search
Const strF As String = _
"urn:schemas:mailheader:subject LIKE '%undeliverable%' or " & _
"urn:schemas:mailheader:subject LIKE '%out of office%' or " & _
"urn:schemas:mailheader:subject LIKE '%failure%' or " & _
"urn:schemas:mailheader:subject LIKE '%delivery status%'"
Const strS As String = "Inbox"
Set objSch = Application.AdvancedSearch(Scope:=strS, Filter:=strF, SearchSubFolders:=True)

End Function

Private Sub Application_AdvancedSearchComplete(ByVal SearchObject As Search)

''deletes unwanted mail returned by the clean up function
Dim schRslts As Results
Set schRslts = SearchObject.Results
For Each Item In schRslts
Item.Delete
Next Item
Set schRslts = Nothing

''deletes sent mail and trash folder
Dim ns As outlook.NameSpace
Set ns = Application.GetNamespace("MAPI")
Dim clr_Fldr As outlook.MAPIFolder
Set clr_Fldr = ns.GetDefaultFolder(olFolderSentMail)
For Each Item In clr_Fldr.Items
Item.Delete
Next Item
Set clr_Fldr = ns.GetDefaultFolder(olFolderDeletedItems)
For Each Item In clr_Fldr.Items
Item.Delete
Next Item
Set clr_Fldr = Nothing
Set ns = Nothing

End Sub