如何在任务更新时触发 ItemChange?

How to trigger ItemChange when a Task is updated?

我从互联网上获取了这段代码,可以自动将已完成的任务发送到特定文件夹(“已完成的任务”)。没用,我点一下完成任务就不动了。

我把msgboxes在代码的三处弹出,看看是哪里出了问题。弹出了初始化框,但是ItemChange对应的框没有弹出,另一个也没有。我的印象是没有调用 ItemChange。

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

我试过了:

编辑:将 myolItems 更正为 olItems,现在它可以工作,但前提是我指向一个任务很少的文件夹: Set myolItems = Session.GetDefaultFolder(olFolderTasks).Folders("Inbox").Items

没有 .Folders(Inbox")

就无法工作

olItems 变量从未初始化。您正在初始化未声明的 myolItems 变量。

我认为 .Items 在默认文件夹之后附加时不会返回项目。
我找到了一种将 olItems 指向当前文件夹的方法,方法是在每次切换文件夹时将其定义为当前文件夹。

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