Problems with “WithEvents” in firtstrigger

天涯浪子 提交于 2019-12-13 05:13:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!