PDA

View Full Version : Outlook VBA - Macro fo Loop through outlook unread emails



Su_80
12-21-2020, 07:30 AM
Hello, I am trying to adapt this code for using the macro only in unread emails in a shared box my Inbox, but I don’t get anything that works. Someone for helping me? THanks in advance.

Public Sub Unread_eMails()

Dim myNameSpace As Outlook.NameSpace

Dim myInbox As Outlook.Folder

Dim myDestFolder As Outlook.Folder


Set myNameSpace = Application.GetNamespace("MAPI")

Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)

Set myDestFolder = myInbox.Folders("CHECK")


For Each MyItem In myInbox 'HERE my macro stopped and I don't know why



If myInbox.UnReadItemCount <> 0 Then 'It does not work


If InStr(MyItem.Body, "alarm") > 0 Then

MyItem.Move myDestFolder

Else

If InStr(MyItem.Subject, "Urgent") > 0 Then

MyItem.Move myDestFolder


End If

End If


MyItem.UnRead = False

End If

Next MyItem

End Sub

gmayor
12-21-2020, 10:36 PM
The following will move any unread e-mail from the Inbox to its CHECK sub folder (case sensitive) that contains 'urgent' in the subject or 'alarm' in the body (case ignored). Other unread e-mails are not moved.
You could instead use a Rule to move the messages that fit the criteria as they arrive.


Public Sub Unread_eMails()
'Graham Mayor - https://www.gmayor.com - Last updated - 22 Dec 2020
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myItem As MailItem
Dim myDestFolder As Outlook.Folder
Dim lngCount As Long
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myDestFolder = myInbox.folders("CHECK")
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)
If InStr(LCase(myItem.Body), "alarm") > 0 Or _
InStr(LCase(myItem.Subject), "urgent") > 0 Then
myItem.Move myDestFolder
myItem.UnRead = False
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

Su_80
12-22-2020, 02:54 AM
Thank you so much "gmayor". It's worked, just perfect!