Delete specific emails based on criteria using VBA in Outlook

Emails can often pile up in our inboxes, leading to clutter and confusion.

Wouldn’t it be great if we could automate the process of sorting through and deleting specific emails based on our custom criteria?

This is where Visual Basic for Applications (VBA) in Outlook steps in.

In this post, we will explore how to use VBA to delete specific emails in Outlook, making your email management more efficient and tailored to your needs.

VBA Code for Deleting Specific Emails

Sub DeleteSpecificEmails()
    Dim myNamespace As Outlook.NameSpace
    Dim myFolder As Outlook.Folder
    Dim myItems As Outlook.Items
    Dim myItem As Object

    Set myNamespace = Application.GetNamespace("MAPI")
    Set myFolder = myNamespace.GetDefaultFolder(olFolderInbox)
    Set myItems = myFolder.Items

    For Each myItem In myItems
        If TypeOf myItem Is Outlook.MailItem Then
            Dim myMail As Outlook.MailItem
            Set myMail = myItem
            ' Define your criteria here
            If myMail.Subject = "Your Specific Criteria" Then
                myMail.Delete
            End If
        End If
    Next myItem
End Sub

Understanding the VBA Code

Let’s break down the code for ease of understanding:

  1. Initialization: We start by declaring and setting the necessary Outlook objects such as NameSpace, Folder, and Items.
  2. Looping Through Emails: The For Each loop iterates through each item in the inbox.
  3. Criteria Check: Inside the loop, we check if the item is an email (MailItem) and then apply our specific criteria (e.g., subject line).
  4. Deletion Action: If the email meets the criteria, it gets deleted using the Delete method.

How to Add VBA Code in Outlook

  1. Open VBA Editor: In Outlook, press Alt + F11 to open the VBA editor or go to the Developer tab
  1. Click on Visual Basic to open the VBA editor.
  1. Insert a Module: Right-click on ThisOutlookSession, select Insert, and then Module.
  1. Paste the Code: Copy the provided VBA code and paste it into the new module window.
  2. Save and Close: Save the module and close the VBA editor.

Executing the VBA Script

  1. Restart Outlook: After adding the code, restart Outlook.
  2. Run the Script: Press Alt + F8, select DeleteSpecificEmails, and click ‘Run’.
  3. Monitor the Results: Check your inbox to ensure the script works as expected.

Related Articles