问题
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