DavidSCowan
Board Regular
- Joined
- Jun 7, 2009
- Messages
- 78
I am using Office 2016 and from Excel and am trying to write a procedure to delete specific emails from my Inbox. I have written it to just delete one sender with the aim of looping through a list of senders once this is working. The macro is supposed to move the designated email to the trash and once moved to be deleted. However, the code below throws up a number of problems.
This works after a fashion – some of the emails are moved to Trash but there are a number of problems:
VBA Code:
Sub DeletingEmailsFromSpecificSenders()
Dim ol As Outlook.Application
Dim ns As Outlook.Namespace
Dim fol As Outlook.Folder
Dim i As Object
Dim mi As Outlook.MailItem
Dim n As Long
Set ol = New Outlook.Application
Set ns = ol.GetNamespace("MAPI")
Set fol = ns.GetDefaultFolder(olFolderInbox)
For Each i In fol.Items
If i.Class = olMail Then
Set mi = i 'doing this provides access to the intellisense
If mi.SenderEmailAddress = "boxoffice@bridgetheatre.co.uk" Then
Set mi = mi.Move(ns.GetDefaultFolder(olFolderDeletedItems))
mi.Delete
n = n + 1
End If
End If
Next i
MsgBox "The number of this item to delete is " & n
End Sub
This works after a fashion – some of the emails are moved to Trash but there are a number of problems:
- None of the emails moved to trash are deleted i.e. deleted from Trash
- There were four emails from the example sender but only two were moved to Trash. The ones that had attachments were not moved (and this has been replicated with other senders).
- There is an additional problem too. Searching the Inbox for the sender that was supposed to be moved indicates that there are still the original four in the Inbox. However, ordering the emails “By From” and scrolling down shows, correctly, that there are only two still in the Inbox (the two that have attachments). How can I get the search facility to yield the correct answer? I understand that this is a 2016 problem which earlier versions don’t suffer from. Can anyone help with this too please.
Thank you in advance.
David