问题
I have this code in a module:
Private WithEvents objNewMailItems As Outlook.Items
Public Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set mainInboxItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub mainInboxItems_ItemAdd(ByVal item As Object)
Call MandarMail.sendOutlookEmail
//this send another email...
End Sub
This is my first trigger, so I don't know if I 'm doing something wrong. The problem is Visual Basic for Applications don't not recognize me this:
Private WithEvents objNewMailItems As Outlook.Items
I'm using Outlook 2013. I need a library or something?
回答1:
If written in Outlook this should work.
You've declared objNewMailItems
but used mainInboxItems
Dim WithEvents objNewMailItems As Items
Public Sub Application_Startup()
Dim objNS As NameSpace
Set objNS = olApp.GetNamespace("MAPI")
Set objNewMailItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub objNewMailItems_ItemAdd(ByVal item As Object)
'This will fire when you receive a new email.
Debug.Assert False
End Sub
Edit - I've found with this that after a while Outlook disables the macros, so have to manually run StartUp
each day. Doesn't matter what I try with the Trust Centre settings - it keeps disabling my code.
回答2:
Thx Darren. I modificated your code and now works fine:
Dim WithEvents objNewMailItems As Items
Public Sub Application_Startup()
Dim objNS As Outlook.NameSpace
Dim olApp As Outlook.Application
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set objNewMailItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub objNewMailItems_ItemAdd(ByVal item As Object)
'This will fire when you receive a new email.
MsgBox ("mail recibi")
End Sub
来源:https://stackoverflow.com/questions/34720620/problems-with-withevents-in-firtstrigger