在某些邮件项目上标记为读取循环错误不一致

时间:2016-06-21 13:45:47

标签: vba outlook outlook-vba

我在一个周末收到4000多封电子邮件,并且整个星期都会通过规则过滤到文件夹中。我创建了一个宏来将所有这些文件夹标记为已读。但是,对于某些邮件项目,它会导致runtime error 91 object variable or with block variable not set错误。

如果我跳过On Error Resume Next的错误,它会遍历所有内容,但不会将一堆邮件项设置为已读。然后我可以重新调整宏以获得大部分剩余的宏。如果我运行宏3-4次,它最终会得到它们。

如何改进此宏以始终将所有项目标记为已读?

Public Function GetInboxFolderID(FolderName As String) As String
    Dim nsp As Outlook.Folder
    Dim mpfSubFolder As Outlook.Folder
    Dim mpfSubFolder2 As Outlook.Folder
    Dim flds As Outlook.Folders
    Dim flds2 As Outlook.Folders

    Set nsp = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
    Set flds = nsp.Folders
    Set mpfSubFolder = flds.GetFirst
    Do While Not mpfSubFolder Is Nothing
        If mpfSubFolder.Name = FolderName Then
            GetInboxFolderID = mpfSubFolder.EntryID
            Exit Function
        End If
        Set flds2 = mpfSubFolder.Folders
        Set mpfSubFolder2 = flds2.GetFirst
        Do While Not mpfSubFolder2 Is Nothing
            If mpfSubFolder2.Name = FolderName Then
                GetInboxFolderID = mpfSubFolder2.EntryID
                Exit Function
            End If
            Set mpfSubFolder2 = flds2.GetNext
        Loop
        Set mpfSubFolder = flds.GetNext
    Loop
End Function

Private Sub processFolder(ByVal oParent As Outlook.MAPIFolder)

        Dim oFolder As Outlook.MAPIFolder
        Dim oMail As Outlook.MailItem
        Dim oFiltered As Outlook.Items

        Set oFiltered = oParent.Items.Restrict("[unread] = true")
        On Error Resume Next
        For Each oMail In oFiltered

            oMail.UnRead = False

        Next

        If (oParent.Folders.Count > 0) Then
            For Each oFolder In oParent.Folders
                processFolder oFolder
            Next
        End If
End Sub

Public Sub markNocAsRead()
    Dim SubFolder As MAPIFolder
    Set SubFolder = Session.GetDefaultFolder(olFolderCalendar).Parent.Folders("NOC Alerts")
    'Application.Session.GetFolderFromID (GetInboxFolderID("NOC Alerts"))
    Call processFolder(SubFolder)
End Sub

1 个答案:

答案 0 :(得分:0)

我能够在上面的评论中听取Ryan Wildry的建议,始终如一地工作。

我替换了我的循环:

Set oFiltered = oParent.Items.Restrict("[unread] = true")
On Error Resume Next
For Each oMail In oFiltered
    oMail.UnRead = False
Next

带有从头到尾迭代的循环:

Set oFiltered = oParent.Items.Restrict("[unread] = true")
For I = oFiltered.Count To 1 Step -1
    Set oMail = oFiltered(I)
    oMail.UnRead = False
Next