【问题标题】:Looping through Mail items but skipping an email循环浏览邮件项目但跳过电子邮件
【发布时间】:2017-12-13 22:26:29
【问题描述】:

我正在尝试遍历邮箱中的所有电子邮件并从中提取附件。如果我没有包含删除,则循环按预期工作。包含删除它适用于第一封电子邮件,并且在“下一个”语句中退出 for 循环,跳过剩余的电子邮件。我可以将删除分离到一个新循环中,但这似乎效率低下。

For Each itm In Inbox.Items

  For Each objAtt In itm.Attachments

    sEmailDate = Format(itm.ReceivedTime, "dd/mm/yyyy")
    sDataDate = Format(DateAdd("d", -1, CDate(sEmailDate)), "dd/mm/yyyy")
    sFileName = objAtt.Filename
    sSubject = itm.Subject

    'Check if the report was sent today
    If sEmailDate = sTodayDate And sFileName = "Report.csv" Then
        bToday = True
    End If

    'Look for Report file
    If sFileName = "Report.csv" Then

        'Save it to the save folder, as the DisplayName. This will overwrite previously saved copies of this file
        objAtt.SaveAsFile saveFolder & "\" & "report" & sSubject & "_" & Format(sDataDate, "yyyymmdd") & ".csv"
        If Err.Number = 0 Then
            itm.Delete 'without this istwill loop correctly
            iReportCount = iReportCount + 1
        Else
            GoTo ExitLoop
        End If

    End If
  Next objAtt

Next itm

【问题讨论】:

标签: excel outlook vba


【解决方案1】:

使用For 循环而不是For Each 一个:

Dim items as Outlook.Items
Set items = Inbox.Items

For i = items.Count to 1 Step -1

  For Each objAtt In itm.Attachments

    sEmailDate = Format(itm.ReceivedTime, "dd/mm/yyyy")
    sDataDate = Format(DateAdd("d", -1, CDate(sEmailDate)), "dd/mm/yyyy")
    sFileName = objAtt.Filename
    sSubject = itm.Subject

    'Check if the report was sent today
    If sEmailDate = sTodayDate And sFileName = "Report.csv" Then
        bToday = True
    End If

    'Look for Report file
    If sFileName = "Report.csv" Then

        'Save it to the save folder, as the DisplayName. This will overwrite previously saved copies of this file
        objAtt.SaveAsFile saveFolder & "\" & "report" & sSubject & "_" & Format(sDataDate, "yyyymmdd") & ".csv"
        If Err.Number = 0 Then
            itm.Delete
            iReportCount = iReportCount + 1
        Else
            GoTo ExitLoop
        End If

    End If
  Next

Next

【讨论】:

    猜你喜欢
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2022-08-14
    • 2021-01-15
    相关资源
    最近更新 更多