Mark harris
Mark harris

Reputation: 543

search for emails with specific subject title IF UNREAD and save attachments into folder

I am using the following vba code which should search for all emails with a specific subject title i.e. with the subject 'test'

Then only if the email is unread then save the attachment from that email into a folder.

There may be one or several emails with the subject test so I want all the unread emails with the subject test to have their attachments saved to the folder.

Here is my code:

Sub Work_with_Outlook()

 Set olApp = CreateObject("Outlook.Application")

     Dim olNs As Outlook.Namespace
     Dim Fldr As Outlook.MAPIFolder
     Dim myItem As Object
     Dim myAttachment As Outlook.Attachment
     Dim I As Long
     Dim olMail As Variant


     Set olApp = New Outlook.Application
     Set olNs = olApp.GetNamespace("MAPI")
     Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
     Set myTasks = Fldr.Items

  Set UnRead = myTasks.Restrict("[UnRead] = False")
  Set olMail = myTasks.Find("[Subject] = ""test""")
  If Not (olMail Is Nothing) And UnRead.Count = 0 Then






    For Each myItem In myTasks
        If myItem.Attachments.Count <> 0 Then
            For Each myAttachment In myItem.Attachments
            If InStr(myAttachment.DisplayName, ".txt") Then
                I = I + 1
                myAttachment.SaveAsFile "\\uksh000-file06\Purchasing\NS\Unactioned\" & myAttachment
                End If
            Next
        End If

    Next


For Each myItem In myTasks
myItem.UnRead = False
Next

  MsgBox "Scan Complete."

  Else
  MsgBox "There Are No New Supplier Requests."
  End If

End Sub

This does work to some degree, if I only have one email with the subject 'test' and it is unread then the script will get the attachment from that email and save it to my folder. However, if I have one email with the subject 'test' which is read and another email with the subject 'test' which is unread then the code won't work?

Please can someone show me where I am going wrong? Thanks in advance

Upvotes: 0

Views: 3927

Answers (1)

Eugene Astafiev
Eugene Astafiev

Reputation: 49395

It looks like you need to combine both comditions into a single one and use the Find/FindNext or Restrict methods to get an instance of the Items class which contains all items correspodning to your conditons. For example:

 Set resultItems = myTasks.Restrict("[UnRead] = False AND [Subject] = ""test""")

See Enumerating, Searching, and Filtering Items in a Folder for information in MSDN.

Also you may find the sample code in the following articles:

Upvotes: 0

Related Questions