enderland
enderland

Reputation: 14135

How can I trigger an event when multiple items added at once to Outlook Folder?

I use event handlers in VBA and Outlook frequently. One of them is one which marks any item which is deleted to be marked as read.

Private Sub deletedItems_ItemAdd(ByVal Item As Object)
    Application_Startup
    On Error Resume Next
    Item.UnRead = False

End Sub

Declared via:

Private WithEvents deletedItems As Outlook.Items

and initialized in Application_Startup as:

Dim olNameSpace As Outlook.NameSpace
Set olNameSpace = olApp.GetNamespace("MAPI")
Set deletedItems = olNameSpace.GetDefaultFolder(olFolderDeletedItems).Items

Unfortunately, this does not affect all the items if I delete multiple items at once.

Is there a way I can do something to hijack this process somehow? I looked into using the _beforeDelete event but you have to set the item correctly each time, which if I could do this problem wouldn't exist anyways.


Apparently I wasn't clear - the use case I have is when I delete messages via the delete key from my inbox, drafts, whatever.

Upvotes: 4

Views: 2352

Answers (2)

Max
Max

Reputation: 759

i have (almost) exactly the same code and it works also for multiple items - only after sleep-mode Outlook seems to forget how to handle deleted items...

Option Explicit
Public WithEvents itDeleted As items

Private Sub Application_Startup()
    Set itDeleted = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderDeletedItems).items
End Sub

Private Sub itDeleted_ItemAdd(ByVal Item As Object)
'MsgBox "deleted-sub fired" 'this only for test-purposes
If TypeOf Item Is MailItem Then
  Item.UnRead = False
End If
End Sub

I think the difference in the definition of "deletedItems" is the problem; that you are not checking the mailitem-property is also not optimal.

Hope this helps, Max

Upvotes: 0

Mathieu Guindon
Mathieu Guindon

Reputation: 71177

You don't have to.

I was curious about your question so I opened up Outlook and wrote this code in ThisOutlookSession:

Private WithEvents items As Outlook.items

Public Sub SetItems()
    Set items = Application.GetNamespace("MAPI") _
                           .GetDefaultFolder(olFolderDeletedItems) _
                           .items
End Sub

Private Sub items_ItemAdd(ByVal Item As Object)

    Dim mail As MailItem

    On Error Resume Next
        Set mail = Item
        Err.Clear
    On Error GoTo 0

    If Not mail Is Nothing Then
        MsgBox mail.Subject
        mail.UnRead = False
    End If

End Sub

Then I ran SetItems from the immediate pane, went to my inbox and deleted a SMS message - as expected mail was Nothing. Then I deleted a single email, and got the message with the mail's subject.

When I selected two emails and hit Delete, the event was fired once for each selected email, so I saw two message boxes - it just works! :)

The Outlook API doesn't seem to offer an event which would handle all deletions at once.

Upvotes: 4

Related Questions