Events是为这个完美的。
当发生密钥更改时,应用程序触发事件。这可以让你避免使用定时循环。
您可以使用WithEvents语句创建一个可以处理事件调用的变量。
在这个例子中,变量f指向收件箱。每当从该文件夹中删除一个项目时,就会调用f_BeforeItemMove
过程。它显示剩下的项目数,减1。我们减去一个,因为事件在删除之前被触发(如果您愿意,这会让您有机会取消它)。
因为我们使用的是object variable,所以我们需要创建并销毁它。当应用程序启动&退出时会发生这种情况。
Private WithEvents f As Folder ' Inbox folder, used to monitor events.
Private Sub Application_Startup()
' Register for events.
Set f = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
End Sub
Private Sub Application_Quit()
' Unregister.
Set f = Nothing
End Sub
Private Sub f_BeforeItemMove(ByVal Item As Object, ByVal MoveTo As MAPIFolder, Cancel As Boolean)
' Called when an item is moved out of the inbox.
' Display the number of items left, after delete.
MsgBox (f.Items.Count - 1)
End Sub
必须将此代码添加到ThisOutlookSession类中。如果粘贴到另一个模块中,启动和退出事件不会触发。
EDIT
原始溶液,上方,是触发之前项被从收件箱中删除。 OP想要刚刚解雇的代码。这个新的解决方案做到了。
Private WithEvents f As Folder ' Inbox folder, used to monitor events.
Private WithEvents i As Items ' Items within folder above
Private Sub Application_Startup()
' Register for events.
Set f = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set i = f.Items
End Sub
Private Sub Application_Quit()
' Unregister.
Set i = Nothing
Set f = Nothing
End Sub
Private Sub i_ItemRemove()
' Called each time an item is moved out of the inbox.
' This can be triggered by moving an item to another folder
' or deleting it.
' Display the new inbox item count.
MsgBox i.Count
End Sub
和以前一样;此代码应放置在ThisOutlookSession
之内。您将需要重新启动Outlook,或手动执行Application_Startup
。
感谢您的回复。我试过这个,不幸的是它不会触发任何东西。我已将代码放在ThisOutlookSession中,并将其指向我要监视的文件夹,但当我删除或移出收件箱中的电子邮件时,它没有做任何事情。 –
对不起,我应该添加;要获得此代码,您需要手动运行Application_Startup或关闭并重新打开Outlook。要手动运行只需点击子内,然后按F5键。为什么?因为需要通过SET语句创建f对象变量。一旦完成,它将开始响应事件。 –
现在,我已重新启动Outlook,这很好。非常感谢。一个问题,但。我需要在邮件项目移动之后运行它,而不仅仅是之前,因为我的下一个代码将检查邮箱计数,并且只有在它等于0时才运行。由于此操作在手边运行,因此它认为邮箱中仍有一封电子邮件我的下一部分没有运行。 –