Type Mismatch in mailitem loop

2019-03-04 14:04发布

问题:

Outlook 2010 VBA. Trying to search for flagged messages in all my folders. Created this:

Private Sub flagrecurse(fold As Variant)

Dim olItem As MailItem
Dim nxtfold As Folder
Dim olFoldVar As Variant

'Test for which folder is being checked
MsgBox (fold.Name)

If fold.Folders.Count > 0 Then
    For Each nxtfold In fold.Folders
        Set olFoldVar = nxtfold
        flagrecurse olFoldVar
    Next nxtfold
Else
    For Each olItem In fold.Items
         'Test for which item is being checked
         If TypeName(olItem) = "MailItem" Then
            MsgBox (olItem.Subject)
            With olItem
                If .FlagRequest <> "" Or .IsMarkedAsTask Then
                    '.TaskDueDate = Now
                    'Sets a reminder today, in case one wasn't set
                    If Not (.ReminderSet) Then
                        .ReminderSet = True
                        .ReminderTime = Now + 2 / 24
                        .Save
                    End If
                End If
            End With
        End If
    Next olItem
End If

End Sub

The issue is I have 744 items in my Inbox, it gets through 8 or 9, then gives me a "Type Mismatch". When I'm debugging, it flags "Next olItem" and when I check the value of "olItem" it resolves to "nothing".

What am I doing wrong?

回答1:

You are assuming that you can only have MailItem objects in the folder. You can also have ReportItem, MettingRequestItem, etc. Declare olItem as a generic Object and check the Class property to be 43 (olMail).