vbaoutlookoutlook-2016

How to trigger ItemChange when a Task is updated?


I took this code from the internet to automatically send the tasks that are completed to a specific folder ("Completed Tasks"). It didn't work, I would click to complete the task and it wouldn't get moved.

I put msgboxes to pop up at three parts of the code to see where the problem is. The initialization box pops up, but the box corresponding to the ItemChange doesn't, and the other one doesn't as well. My impression is that the ItemChange isn't being called.

Public WithEvents olItems As Outlook.Items

Public Sub Application_Startup()
    Set olItems = Session.GetDefaultFolder(olFolderTasks).Items
    MsgBox ("initialized")
End Sub

Public Sub olItems_ItemChange(ByVal Item As Object)
    Dim CompTaskf As Folder
    MsgBox ("detected change")
    
    If Item.Complete = True And Item.IsRecurring = False Then
        MsgBox ("condition met")
        Set CompTaskf = Session.GetDefaultFolder(olFolderTasks).Folders("Completed Tasks")
        Item.Move CompTaskf
    End If
End Sub

I tried:

Edit: corrected myolItems to olItems, now it works but only if I point to a single folder with few tasks: Set myolItems = Session.GetDefaultFolder(olFolderTasks).Folders("Inbox").Items

It doesn't work without the .Folders(Inbox")


Solution

  • I thought .Items wasn't returning the items when attached right after the default folder.
    I found a way to point olItems to the current folder by defining it as so every time I switch folders.

    Public WithEvents olItems As Outlook.Items
    Public WithEvents daFolder As Outlook.Explorer
    
    Public Sub Application_Startup()
        Set daFolder = Application.ActiveExplorer
        'MsgBox ("initialized")
    End Sub
    'Sets daFolder as the active explorer window on startup, 
    ' apparently necessary because i can't put
    ' Application.ActiveExplorer_FolderSwitch() as the sub
    
    Public Sub daFolder_FolderSwitch()
        Set olItems = Application.ActiveExplorer.CurrentFolder.Items
    End Sub
    'Every time i switch between folders, set olItems as the items of the current folder
    
    Public Sub olItems_ItemChange(ByVal Item As Object)
        Dim CompTaskf As Folder
        'MsgBox ("detected change")
        If TypeName(Item) = "TaskItem" And Item.Complete = True And Item.IsRecurring = False Then 'This verification that it's a task item is necessary, otherwise the code may crash
            'MsgBox ("condition met")
            Set CompTaskf = Session.GetDefaultFolder(olFolderTasks).Folders("Completed Tasks") 'Set folder i want to move tasks to
            Item.Move CompTaskf 'Move task to the folder
        End If
    End Sub