【问题标题】:VBA MailItem.Add only triggering once?VBA MailItem.Add 只触发一次?
【发布时间】:2019-03-19 15:31:49
【问题描述】:

我编写了一段简短的代码来在电子邮件到达邮箱时执行某些操作,但它似乎只适用于在保存代码后立即到达的第一封电子邮件,之后什么都没有发生用于后续电子邮件。

我在代码上放了个watch,没有触发任何东西,所以不只是后续代码中的后续错误。

代码是(在会话对象中):

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

任何可以提供的指导或指示将不胜感激!

【问题讨论】:

  • 如何定义objItems
  • 您好,抱歉,我不太明白这个问题!
  • 您在使用对象时没有声明它们(或者至少没有显示它们是如何声明的)。这里唯一声明的对象是objWathchFolder,但我们没有objNSobjItem 的声明。请注意,如果它们没有被声明为全局,它们只有一个语言环境声明范围(并且在 Application_Startup 的末尾被销毁
  • 道歉,现在和你在一起: Private objNS as Outlook.NameSpace Private WithEvents objItems as Outlook.Items
  • edit您的问题添加声明

标签: vba outlook mailitem


【解决方案1】:

如果您使用 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?

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 2021-03-22
    • 2015-09-07
    • 2016-11-10
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多