Home > database >  VBA to Perm Delete Outlook mail
VBA to Perm Delete Outlook mail

Time:12-10

I have the below code which works great to delete a mail from inbox permanently. However, when ppl respond to a meeting invite, those mails we get to say the person has accepted the meeting doesnt delete.

When I click on that mail and run this code it does not delete?

Here is what I am using

Sub PermDelete(Item As Outlook.MailItem)
' First set a property to find it again later
Item.UserProperties.Add "Deleted", olText
Item.Save
Item.Delete

'Now go through the deleted folder, search for the property and delete item
Dim objDeletedFolder As Outlook.Folder
Dim objItem As Object
Dim objProperty As Variant

Set objDeletedFolder = Application.GetNamespace("MAPI"). _
  GetDefaultFolder(olFolderDeletedItems)
For Each objItem In objDeletedFolder.items
    Set objProperty = objItem.UserProperties.Find("Deleted")
    If TypeName(objProperty) <> "Nothing" Then
        objItem.Delete
    End If
Next

End Sub

CodePudding user response:

In the code your function accepts an instance of the MailItem class only. But an Outlook folder may contain different types of items - appointments, documents, notes and etc. To differentiate them at runtime you can use the following construction:

Dim obj As Object

If TypeName(obj) = "MailItem" Then
  ' your code for mail items here
End If

So, you need to declare the function in the following way (if you don't need to do separate actions for different kind of items):

Sub PermDelete(Item As Object)
' First set a property to find it again later
Item.UserProperties.Add "Deleted", olText
Item.Save
Item.Delete

'Now go through the deleted folder, search for the property and delete item
Dim objDeletedFolder As Outlook.Folder
Dim objItem As Object
Dim objProperty As Variant

Set objDeletedFolder = Application.GetNamespace("MAPI"). _
  GetDefaultFolder(olFolderDeletedItems)
For Each objItem In objDeletedFolder.items
    Set objProperty = objItem.UserProperties.Find("Deleted")
    If TypeName(objProperty) <> "Nothing" Then
        objItem.Delete
    End If
Next

End Sub

CodePudding user response:

Set Item to a generic Object

Example on selected item

Option Explicit
Public Sub Example()
    Dim obj As Object
    
    Set obj = ActiveExplorer.Selection.Item(1)
    obj.Delete

End Sub
  • Related