firtstrigger中“WithEvents”的问题

时间:2016-01-11 11:38:59

标签: vba outlook outlook-vba

我在一个模块中有这个代码:

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

这是我的第一次触发,所以我不知道自己做错了什么。问题是Visual Basic for Applications不认识我:

Private WithEvents objNewMailItems As Outlook.Items

我正在使用Outlook 2013.我需要一个库或什么?

2 个答案:

答案 0 :(得分:2)

如果用Outlook编写,这应该有用 您已声明objNewMailItems但已使用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

编辑 - 我发现这样一段时间后Outlook会禁用宏,因此必须每天手动运行StartUp。无论我尝试使用信任中心设置 - 它都会一直禁用我的代码。

答案 1 :(得分:0)

达克伦。我修改了你的代码,现在工作正常:

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