PDA

View Full Version : [SOLVED:] Trying to get macro to call on unread emails only



vegtabet
08-04-2023, 06:18 AM
Hopefully an easy one.

I'm trying to get a macro to run against unread emails only. I have the below so far but it only runs on the selected email, not all unread emails:


Public Sub Unread_Emails()
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myItem As MailItem


Dim lngCount As Long
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)


MsgBox myInbox.UnReadItemCount
If myInbox.UnReadItemCount > 0 Then
For lngCount = myInbox.items.Count To 1 Step -1
If TypeName(myInbox.items(lngCount)) = "MailItem" Then
If myInbox.items(lngCount).UnRead = True Then
Set myItem = myInbox.items(lngCount)
Call my_Sub




End If
End If
End If
DoEvents
Next lngCount
End If
Set myNameSpace = Nothing
Set myInbox = Nothing
Set myItem = Nothing
Set myDestFolder = Nothing
End Sub


What do I need to change to get this to only operate on unread emails?

gmayor
08-04-2023, 09:37 AM
The code you posted has an extra End If line, but that aside it does act on unread items in the Inbox. The burning question relates to my_Sub, which you haven't shared. It seems likely that any issues relating to the processing should be found there.

Option Explicit

Public Sub Unread_Emails()
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myItem As MailItem
Dim lngCount As Long
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)


MsgBox myInbox.UnReadItemCount
If myInbox.UnReadItemCount > 0 Then
For lngCount = myInbox.Items.Count To 1 Step -1
If TypeName(myInbox.Items(lngCount)) = "MailItem" Then
If myInbox.Items(lngCount).UnRead = True Then
Set myItem = myInbox.Items(lngCount)
Debug.Print myItem.Subject
'Call my_Sub
End If
End If
DoEvents
Next lngCount
End If
Set myNameSpace = Nothing
Set myInbox = Nothing
Set myItem = Nothing
End Sub

vegtabet
08-04-2023, 02:01 PM
Thanks Graham - I think you have answered my question.