我已经写了一段简短的代码来在电子邮件到达邮箱时执行某些操作,但是它似乎只适用于代码保存后立即到达的第一封电子邮件,此后什么也没发生用于后续电子邮件。
我已经监视了代码,并且什么都没有触发,所以这不仅仅是后续代码中的后续错误。
代码为(在会话对象中):
Option Explicit
Private objNS As Outlook.Namespace
Private WithEvents objItems As Outlook.Items
Private sub Application_Startup()
Dim objWatchFolder as Outlook.Folder
Set objNS = Application.Getnamespace("MAPI")
Set objWatchFolder = objNS.GetDefaultFolder(olFolderInbox)
Set objItems = objWatchFolder.Items
End Sub
Private Sub objItems_ItemAdd(ByVal Item as Object)
' Do this, that, the other, passing the e-mail to other subroutines
' No problems in this code.
End Sub
我们将不胜感激!
答案 0 :(得分:0)
如果使用WithEvents,请重新启动Outlook。但是,请尝试以下代码:
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
参考链接:How do I trigger a macro to run after a new mail is received in Outlook?