【问题标题】:Item_Add code doesn't execute when item moved by inbox rule收件箱规则移动项目时不执行 Item_Add 代码
【发布时间】:2021-07-07 18:47:09
【问题描述】:

我有一些通过电子邮件发送给我的每日报告(Excel 文件)。收件箱规则将电子邮件移动到标题为“每日报告”的 Outlook 文件夹。

当电子邮件按规则移入文件夹时,我希望附件自动保存到文件夹并按日期组织。类似于:C:\Desktop\ReportName\2019\11-2019\11-05-2019 Report Name.xlsx

我有几个问题。

  1. 当规则移动电子邮件时,代码不会运行,只有在我手动移动电子邮件时才会运行。
  2. 它会创建新目录并保存第一封电子邮件的附件,但其他电子邮件会导致路径/访问错误引用
MkDir ("C:\Users\username\Desktop\Outlook Test Folder\" & Format(Date, "YYYY"))
Private WithEvents olItems As Outlook.Items

Private Sub Application_Startup()
    Dim objNS As Outlook.NameSpace

    Set objNS = GetNamespace("MAPI")
    Set olItems = objNS.GetDefaultFolder(olFolderInbox).Parent.Folders("Daily Reports").Items
    Set objNS = Nothing
End Sub

Private Sub olItems_ItemAdd(ByVal Item As Object)
    Dim NewMail As Outlook.MailItem
    Dim Atts As Attachments
    Dim strPath As String
    Dim attName As String
 
    If Item.Class = olMail Then
        Set NewMail = Item
    End If
       
    If Dir("C:\Users\username\Desktop\Outlook Test Folder\" & Format(Date, "YYYY"), vbDirectory) = "" Then
        MkDir ("C:\Users\username\Desktop\Outlook Test Folder\" & Format(Date, "YYYY"))
    End If

    If Dir("C:\Users\username\Desktop\Outlook Test Folder\" & Format(Date, "YYYY" & "\" & Format(Date, "MM-YYYY")), vbDirectory) = "" Then
        MkDir ("C:\Users\username\Desktop\Outlook Test Folder\" & Format(Date, "YYYY") & "\" & Format(Date, "MM-YYYY"))
    End If
   
    If InStr(LCase(Item.Subject), "daily applications was executed at") > 0 Then
       strPath = "C:\Users\username\Desktop\Outlook Test Folder\" & Format(Date, "YYYY") & "\" & Format(Date, "MM-YYYY")
       attName = " Daily Applications.Xlsx"
    ElseIf InStr(LCase(Item.Subject), "dailyopenedcalls was executed at") > 0 Then
            strPath = "C:\Users\username\Desktop\Outlook Test Folder\" & Format(Date, "YYYY") & "\" & Format(Date, "MM-YYYY")
            attName = " Daily Opened Calls.Xlsx"
    End If

    Set Atts = Item.Attachments

    If Atts.Count > 0 Then
        For Each Att In Atts
            If InStr(LCase(Att.FileName), ".xlsx") > 0 Then
                Att.SaveAsFile strPath & "\" & Format(Date, "mm-dd-yyyy") & attName
            End If
        Next
    End If

End Sub

【问题讨论】:

    标签: vba outlook


    【解决方案1】:
    1. 仅当我手动移动电子邮件时,规则才移动电子邮件时代码不会运行。

    如果将多个项目移动到一个文件夹,ItemAdd 事件可能不会被触发。这是 Outlook 中的一个已知问题。

    另一个可能的原因是 Outlook 规则在 Application_Startup 之前运行。

    1. 它可以很好地创建新目录并保存第一个电子邮件附件,但是其他电子邮件会导致路径/访问错误

    确保使用路径或文件中允许的符号。我建议尝试手动创建相同的路径,以使路径中只使用允许的符号。

    【讨论】:

    • Eugene, 1. 报告出现的时间完全不同,它一次只能移动一项。不过,这很好知道 - 是否有解决此问题的方法? 2. 我刚刚尝试对其进行硬编码——同样的问题。尽管由于目录已经存在,该行甚至不应该运行?
    • 作为一种解决方法,您可以使用计时器来检查项目数量并处理新项目。
    • 已解决:我的 if 语句中缺少一个结束括号,导致路径问题。手动运行规则时似乎不会触发项目添加,但自动运行时确实有效。
    猜你喜欢
    • 1970-01-01
    • 2019-05-06
    • 2015-09-06
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多