Reputation: 11
I have a folder in Outlook named "Questionnaire", and within that folder, I have several subfolders. The code loops through all the subfolders, within each subfolder, it finds all the unread items (specifically emails) and does something with the emails.
When the code is run on my coworker's computer, a Type Mismatch error is triggered at the line
Set objMails = olFolder2.Items
Similar threads point to an item that is non-mail causing the mismatch error. I confirmed with my coworker that there are no items other than emails in the subfolder. I tested on my own Outlook by dragging a calendar invite into the first subfolder, and the error occurred at the line
For Each objMail In objMails
Which would makes a lot more sense if the problem was to be stemming from having a non-mail item in the subfolder.
Here is a skeleton of my code:
'Define outlook folder variables
Dim olFolder1 As Outlook.Folder, olFolder2 As Outlook.Folder
Set olFolder1 = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Folders("Questionnaire")
For Each olFolder2 In olFolder1.Folders 'Loop through all the folders in the Questionnaire folder
Dim objMails As Outlook.Items
Set objMails = olFolder2.Items
Dim objMail As Outlook.MailItem
sFilter = "[UNREAD]=TRUE"
Set objMails = objMails.Restrict(sFilter)
For Each objMail In objMails
'CODE TO DO SOMETHING WITH EACH EMAIL IN THE SUBFOLDERS
Next
Next
Upvotes: 1
Views: 567
Reputation: 66215
You are assuming you can only have MailItem
objects in the folder. Declare objMail
variable as a generic Object
rather than MailItem
.
Upvotes: 0
Reputation: 508
'escape multiple declaration in each loop iteration
Dim objMails As Outlook.Items
Dim objMail 'As Object
sFilter = "[UNREAD]=TRUE"
For Each olFolder2 In olFolder1.Folders
Set objMails = olFolder2.Items.Restrict(sFilter)
For Each objMail In objMails
If objMail.Class = olMail Then
'CODE TO DO SOMETHING WITH EMAIL only
End if
Next objMail 'explicit loop variable
Next olFolder2 'explicit loop variable
Upvotes: 1