从Excel中使用Outlook事件

我试图从Excelmacros中的Outlook对象模型中使用“ItemAdd”事件MSDN链接这里 ; 但是,我还没有find一种方法来利用Excel以外的事件。

我的预期用例是监视共享邮箱中收到的项目并logging他们的接收。 我目前正在一个计时器上运行一个循环,检查新的电子邮件,但是我希望只要有可能就logging每次事件触发。

不幸的是,我无法直接从Outlook运行任何macros,所以我只能从其他Office应用程序访问Outlook对象模型。

你可以这样做,但是你需要在Excel中使用一个Class模块来完成它。

类模块 – “myOutlook”或称之为任何你想要的。

Private WithEvents myItems As Outlook.Items Private Sub Class_Initialize() Dim oNS As Namespace Dim myOL As Outlook.Application Set myOL = New Outlook.Application Set oNS = myOL.GetNamespace("MAPI") Set myItems = oNS.GetDefaultFolder(olFolderInbox).Items 'Set this equal to the folder you wish to use this on End Sub Private Sub myItems_ItemAdd(ByVal Item As Object) Debug.Print "Got_EMAIL!!!" End Sub 

然后,在一个常规模块中这样做:

  Dim myOutlook As myOutlook Sub TestSub() Set myOutlook = New myOutlook End Sub 

一旦你初始化你的用户定义的类的实例,事件将被它捕获。

显然,您需要将“myItems”对象设置为链接到正确的收件箱。 对于我的,它只是链接到我的默认邮箱,这是最容易进行testing。