Type Mismatch error when items in Inbox declared as mailitems

有些话、适合烂在心里 提交于 2019-12-11 06:56:01

问题


I have the following VBA code in Outlook to move mail to a personal folder if it is old. Here is the code:

I get an exception on the line Next objItem (looking at the watch it is set to nothing).

What would cause objItem to be null and thus cause a Type Mismatch exception in the Next objItem line?

Sub MoveOldMailFromInbox()

Dim objFolder As Outlook.MAPIFolder
Dim objNS As Outlook.NameSpace, objItem As Outlook.MailItem, mail As Outlook.MailItem

Set objNS = Application.GetNamespace("MAPI")

Dim Inbox As MAPIFolder
Set Inbox = objNS.GetDefaultFolder(olFolderInbox)

Dim mailToMove As New Collection

Dim EightyFiveDaysAgo As Date
EightyFiveDaysAgo = DateAdd("d", -85, Date)

Set objFolder = objNS.Folders("PersonalFolders").Folders("InboxOlderThan85Days")
If objFolder Is Nothing Then
    MsgBox "This folder doesn't exist!", vbOKOnly + vbExclamation, "INVALID FOLDER"
End If

For Each objItem In Inbox.Items
    If objFolder.DefaultItemType = olMailItem Then

        If objItem.Class = olMail And objItem.ReceivedTime < EightyFiveDaysAgo Then

            mailToMove.Add objItem

        End If
    End If
Next objItem


For Each mail In mailToMove
    mail.UnRead = False
    mail.Move objFolder
Next mail

Set objItem = Nothing
Set objFolder = Nothing
Set objNS = Nothing

End Sub

回答1:


You're iterating through Inbox.Items but your variable objItem is defined as MailItem - an item in your inbox might not always be a MailItem.

Try

Dim objItem as Object


来源:https://stackoverflow.com/questions/11729903/type-mismatch-error-when-items-in-inbox-declared-as-mailitems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!