每次电子邮件到达Outlook 2007中的某个子文件夹时,如何设置宏才能启动?

时间:2012-09-17 10:32:37

标签: excel vba excel-vba outlook

我有一个宏可以在子文件夹中导出相关的电子邮件字段,但我需要它在每次收到新电子邮件时自动运行。实际上我只想要导出主题行,是否有一个脚本会在电子邮件登陆“M_M_Asia”时触发该宏('ExportMessagesToExcel')?

我在Outlook 2007中。

如果有人能提供帮助,我将永远感激不尽。干杯。

2 个答案:

答案 0 :(得分:0)

  1. 您应该可以使用Application_NewMail模块中的NewMailEx(或ThisOutlookSession)事件来调用您自己的宏。

  2. 另一种方法是创建运行VBA脚本的规则,但是VBA sub需要处理MailItem参数:

    Option Explicit
    
    Sub MyVBARule(poMail As MailItem)
    
    End Sub
    

答案 1 :(得分:0)

或者您可以添加'ItemAdd'事件处理程序,例如:

Option Explicit

Private Const ASIA_FOLDER_NAME As String = "M_M_Asia"
Private WithEvents m_outlookFolderItems As Outlook.Items

Private Sub Application_Startup()
    Initialize_Handler
End Sub

Private Sub m_outlookFolderItems_ItemAdd(ByVal Item As Object)
    ' You have new mail in folder ASIA_FOLDER_NAME
    RunExcelMacro
End Sub

Private Sub Initialize_Handler()
    Dim outlookFolder As Outlook.MAPIFolder
    Dim defaultInboxFolder As Outlook.MAPIFolder
    Dim outlookNameSpace As Outlook.NameSpace

    Set outlookNameSpace = Outlook.GetNamespace("MAPI")
    Set defaultInboxFolder = outlookNameSpace.GetDefaultFolder(olFolderInbox)
    Set outlookFolder = defaultInboxFolder.Folders(ASIA_FOLDER_NAME)
    Set m_outlookFolderItems = outlookFolder.Items
End Sub

Public Sub RunExcelMacro()
    On Error GoTo RunExcelMacro_Err

    Const path As String = "C:\temp\Excel_VBA\"
    Const fileName As String = "CallMeFromOutloouk.xlsm"
    Const macroName As String = "CallMeFromOutlook"

    Dim excelObject As Object
    Dim workbookObject As Object

    Set excelObject = CreateObject("Excel.Application")

    On Error Resume Next
    Set workbookObject = excelObject.Workbooks(fileName)
    On Error GoTo RunExcelMacro_Err

    If workbookObject Is Nothing Then
        Set workbookObject = excelObject.Workbooks.Open(path & fileName)
    End If

    excelObject.Run fileName & "!" & macroName

    Exit Sub

RunExcelMacro_Err:
    MsgBox Err.Description
End Sub