I want to delete an older email when a new message comes in (they have the same subject line).
This run a script sample is perfect to use with status reports and similar messages where you really only need to keep the most recent copy. For it to work, the messages need to have the same subject line (and the subject should be unique, because all messages matching the condition will be deleted.)
To use, create a Rule that checks the message subject and choose Run a Script as the action, selecting this script. The macro checks the Item.Subject, so if you need to run it on messages with different subjects you can use one rule.
While it only runs if Outlook is open, old messages won't pile up, as it deletes all older messages that meet the conditions when Outlook is open.
See Outlook's Rules and Alerts: Run a Script for more information on using Run A Script rules.
Sub DeleteOlderMessages(Item As Outlook.MailItem) Dim objInbox As Outlook.MAPIFolder Dim intCount As Integer Dim objVariant As Variant Set objInbox = Session.GetDefaultFolder(olFolderInbox) ' Remove these lines if you don't want to add a category Item.Categories = "Delete Older" Item.Save For intCount = objInbox.Items.Count To 1 Step -1 Set objVariant = objInbox.Items.Item(intCount) If objVariant.MessageClass = "IPM.Note" Then If objVariant.Subject = Item.Subject And objVariant.SentOn < Item.SentOn Then objVariant.Delete Else End If End If Next Set objInbox = Nothing End Sub
ItemAdd macro version
This version of the macro watches a specific folder for new items, in this example it is watching a subfolder under the Inbox. See Working with VBA and non-default Outlook Folders for code samples to use other folders.
This macro goes into ThisOutlookSession.
Option Explicit Private objNS As Outlook.NameSpace Private WithEvents objItems As Outlook.items Private Sub Application_Startup() Dim objWatchFolder As Outlook.Folder Set objNS = Application.GetNamespace("MAPI") 'Set the folder and items to watch: Set objWatchFolder = objNS.GetDefaultFolder(olFolderInbox).Folders("My Folder") Set objItems = objWatchFolder.items Set objWatchFolder = Nothing End Sub Private Sub objItems_ItemAdd(ByVal Item As Object) Dim intCount As Integer Dim objVariant As Variant For intCount = objItems.Count To 1 Step -1 Set objVariant = objItems.Item(intCount) If objVariant.Subject = Item.Subject And objVariant.SentOn < Item.SentOn Then objVariant.Delete Else End If Next End Sub
How to use macros
First: You will need macro security set to low during testing.
To check your macro security in Outlook 2010 or 2013, go to File, Options, Trust Center and open Trust Center Settings, and change the Macro Settings. In Outlook 2007 and older, it’s at Tools, Macro Security.
After you test the macro and see that it works, you can either leave macro security set to low or sign the macro.
Open the VBA Editor by pressing Alt+F11 on your keyboard.
To put the code in a module:
- Right click on Project1 and choose Insert > Module
- Copy and paste the macro into the new module.
More information as well as screenshots are at How to use the VBA Editor
More Information
More Run a Script Samples:
- Autoaccept a Meeting Request using Rules
- Automatically Add a Category to Accepted Meetings
- Blocking Mail From New Top-Level Domains
- Convert RTF Messages to Plain Text Format
- Create a rule to delete mail after a number of days
- Create a Task from an Email using a Rule
- Create an Outlook Appointment from a Message
- Create Appointment From Email Automatically
- Delegates, Meeting Requests, and Rules
- Delete attachments from messages
- Forward meeting details to another address
- How to Change the Font used for Outlook's RSS Feeds
- How to Process Mail After Business Hours
- Keep Canceled Meetings on Outlook's Calendar
- Macro to Print Outlook email attachments as they arrive
- Move messages CC'd to an address
- Open All Hyperlinks in an Outlook Email Message
- Outlook AutoReplies: One Script, Many Responses
- Outlook's Rules and Alerts: Run a Script
- Process messages received on a day of the week
- Read Outlook Messages using Plain Text
- Receive a Reminder When a Message Doesn't Arrive?
- Run a script rule: Autoreply using a template
- Run a script rule: Reply to a message
- Run a Script Rule: Send a New Message when a Message Arrives
- Run Rules Now using a Macro
- Run-a-Script Rules Missing in Outlook
- Save all incoming messages to the hard drive
- Save and Rename Outlook Email Attachments
- Save Attachments to the Hard Drive
- Save Outlook Email as a PDF
- Sort messages by Sender domain
- Talking Reminders
- To create a rule with wildcards
- Use a Macro to Copy Data in an Email to Excel
- Use a Rule to delete older messages as new ones arrive
- Use a run a script rule to mark messages read
- Use VBA to move messages with attachments
Is there a video on how to do this?
No, but I will make one.
Can this be done without the user of macros?
No, rules don't support this on their own.
This is the only working solution I have found so far without installing any add ons! thanks!. Would it be possible to delete the new ones instead of keeping the latest?
Hello - Appreciate all the macros and the work it took to compile all these. Nice that these macros work after 5+ years of being posted:-)
I have implemented the version called by an Outlook rule as well as the ItemAdd macro version and both work until they encounter an email that has the same date and time (which occasionally happens when I receive emails generated by an inhouse application). I've tried to modify the if statement controlling what emails are deleted based on the subject and time and can't seem to find the correct combination. What happens is neither email is deleted as neither email would match the if statement.
How can the macro (preferably the macro run by a rule) delete one of the matching emails with the same date and time?
Any assistance would be appreciated.
I m trying to use this script and it doesnt work. my current rule is set to move mails from a group to a folder(say group1) same level as Inbox.
i want to run this rule on group1 and my expectation are , it should delete an older email when a new message comes with the same Subject
Rules only run on the inbox. You can run it on the folder later and it should work. If you want it to work as the messages arrive, you need to move the message using the script - you cant mix actions and scripts.
you'll need to change this line to watch the folder:
Set objInbox = Session.GetDefaultFolder(olFolderInbox).parent.folders("group1")
to move the message, use this after the search:
item.move objInbox
Thanks , I use outlook 2016 . I have another question.
I have a folder called group1 , which has about 500 mails a day .
can you help me with a script which can keep the latest mail based on the subject.
I added an itemadd macro to the page - it will work better with high volume. You can use a rule to move mail into the folder and the itemadd will do the search. If there are a lot of messages in the folder to search, it will be slow - to speed it up, you can limit the search to the newest 50 messages or so.
when I run the script it gives me an error script ** doesn't exist or is invalid
are you using the run a script version or the new itemadd version?
The itemadd macro runs on its own, not in a rule.
I did a copy / paste of your Code "ItemAdd macro version" using ALT + F11 and saved them under "This OutlookSession" but I don't see any mails getting deleted. Do I need to do something else to make this work.
when I try to add it in rule I get the error mentioned in the previous post.
you either need to restart outlook or click in the application_startup macro and press Run.
Just to add, when I restart outlook
run-time error '-2147221233(8004010f)': The attempted operation failed. An object could not be found.
Debug pointing to
Set objWatchFolder = objNS.GetDefaultFolder(olFolderInbox).Folders("My Folder")
Do you have a subfolder of the Inbox called My Folder? If it can't find the folder, it definitely will error.
Yes I have them but it doesn't work.
if you get errors after restarting outlook... then its not macro security settings.
i don't know what to say - it is working on my test system.
Yes I fixed it , I added it as parent.folders but its not deleting mails on the folder.
Are the subjects identical and sent at an earlier time? If there are a lot of messages in the folder and high traffic, it can be overwhelming for the macro - you'll need to limit it to like the last 30 or 50.
I think this is how i did it when i had 3000+ messages and needed to limit it to recent messages (that macro is on my office computer) -
For intCount = objItems.Count To objItems.Count - 50 Step -1
Do I need to restart outlook everytime or does it run at the backend always?
Just wanted to thank you for all the help.
it runs in the background - but if you are editing it, you either need to restart outlook or click in the application run macro then click Run to kick start it with the changes.
Thanks, Last Query :
Can you do this for 2-3 Folders in Parallel ?
You can - you need to reference each folder in the application startup macro and create an itemadd macro for each. You can do it something like this and to share the macro that does the work -
Private Sub objItems_ItemAdd(ByVal Item As Object)
FindDuplicates item
End sub
Private Sub objItemsFolder_ItemAdd(ByVal Item As Object)
FindDuplicates item
End sub
Private Sub FindDuplicates(ByVal Item As Object)
Dim intCount As Integer
Dim objVariant As Variant
For intCount = objItems.Count To 1 Step -1
Set objVariant = objItems.Item(intCount)
If objVariant.Subject = Item.Subject And objVariant.SentOn < Item.SentOn Then objVariant.Delete Else End If Next End Sub
Rule in Outlook: Mail from Public Group Move to Folder say Time.
Need a Script to run on the Folder (Time) which will keep latest mail on a particular Subject and move the remaining one to a new folder(say Time1)
This assumes the Time and time1 folders are a subfolder of the inbox:
Set objInbox = Session.GetDefaultFolder(olFolderInbox).folders("Time")
Set objTime1 = Session.GetDefaultFolder(olFolderInbox).folders("Time1")
then change objVariant.Delete to
objVariant.move objTime1
objVariant.Delete
I am not sure I understand. Is your script:
a) Deleting all emails with the same subject of a newer email, whatever is the subject
OR
b) Deleting all emails with the same specific subject X of a newer email
It's a run a script rule, so you'd use whatever condition you want to limit the messages that are touched by the script - it can be sender, subject - any available rule condition. If an incoming message meets the conditions in the rule, the macro looks for older messages matching the subject of the new message.
If you want it to apply to all messages, leave the rule conditions blank.
Thanks for all your scripts! Very helpful!
Hoping you can give me some guidance ...
I'm trying to use an existing script but need to make an adjustment or two ... using DeleteOlderMessages ...
I need the script to categorize the incoming email as 'Most Recent' but then change the category to '*Disregard' when it's deleted ...
and I'd rather move that email to another folder instead of deleting it ... i'm having the biggest issue with changing the category upon moving/deleting ...
any suggestions?
you may need to change it before moving and may need to save the message after setting the category.
' Remove these lines if you don't want to add a category
Item.Categories = "Most Recent"
Item.Save
and
If objVariant.Subject = Item.Subject And objVariant.SentOn < Item.SentOn Then objVariant.categories = "Disregard" objvariant.save ' move code goes here
Perfect! thanks!