收到新的Outlook邮件时无法运行VBA ItemAdd宏

时间:2011-05-25 15:09:19

标签: vba outlook

所以我研究了Outlook VBA ItemAdd事件并创建了一个跟随该示例的类模块,但由于某种原因,当我收到新消息时,我的宏不会触发。它是一个宏,用于解析电子邮件中的数据,然后将其保存到Excel文件中。宏的解析部分工作得很好,因为我在它自己的模块中工作,我可以手动运行,但我还试图在每次收到特定消息的新副本时附加新数据。我有一个规则,将这些电子邮件转发到特殊文件夹,文件夹X,我希望代码搜索新邮件。这是我的代码,它位于类模块中。任何想法为什么这不会自动运行?谢谢!

Public WithEvents myOlItems As Outlook.Items


Public Sub Initialize_handler()

   ' Reference the items in the Inbox. Because myOlItems is declared
   ' "WithEvents" the ItemAdd event will fire below.
   Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders("Folder X").Items


End Sub

Private Sub myOlItems_ItemAdd(ByVal Item As Object)


    Dim objMail As Outlook.MailItem
    Dim count As Integer
    Dim myTitlePos As Integer
    Dim myTitleLen As Integer
    Dim myVarPos As Integer
    Dim myVarLen As Integer
    Dim strPrice As String
    Dim strYear As String
    Dim myVarCRLF As Integer
    Dim myDate As Date
    Dim newLineTest As String


      ' Check to make sure it is an Outlook mail message, otherwise
      ' subsequent code will probably fail depending on what type
      ' of item it is.

      If TypeName(Item) = "MailItem" Then

      'This is where all the working data parsing takes place.

      End If


End Sub

2 个答案:

答案 0 :(得分:1)

而不是尝试在ThisOutlookSession中初始化例程,管理规则&警报运行脚本,您的脚本将成为您的常规。 -Redplaya

答案 1 :(得分:0)

这里只是一个健全性检查...你创建了这个类的实例吗?

即。类似的东西:

Dim c As MyClass
Private Sub Application_Startup()
    c = New MyClass
    ' If you don't rename Initialize_handler, you'll need:
    ' c.Initialize_handler
End Sub
在ThisOutlookSession ......

我希望您也希望将Initialize_handler更改为Class_Initialize,除非您想要明确调用它...