Events 非常适合。
当按键发生变化时,应用程序会触发事件。这样可以避免使用定时循环。
您可以使用WithEvents 语句创建一个可以处理事件调用的变量。
在本例中,变量 f 指向收件箱。每当从此文件夹中删除项目时,就会调用f_BeforeItemMove 过程。它显示剩余的项目数减一。我们减去一个,因为事件是在删除之前触发的(如果您愿意,您可以有机会取消它)。
因为我们使用的是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 类。如果粘贴到另一个模块中,启动和退出事件将不会触发。
编辑
上面的原始解决方案是在从收件箱中删除项目之前触发的。 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。