0

I want to download an attachment from Outlook 2010. The subject of the mail containing the attachment keeps changing. The subject names are in the following format:

"2010 (random name) Sigma Report"

"2011 (random name) Sigma Report"

Now I want to download the first Sigma Report. How shall I connect to Outlook and download this? The following is the code that I have used so far. I'm getting type mismatch in the first 'For' statement.

Sub Attachment_Click()
Const olFolderInbox As Integer = 6
Const AttachmentPath As String = "D:\Documents and Settings\rahul.baskaran\Desktop\"
Dim OApp As Object, ONS As Object, OInb As Object
Dim OItem, OAtch As Object
Dim OFind As Object
Dim OMail As Object

Set OApp = GetObject(, "Outlook.application")
Set ONS = OApp.GetNamespace("MAPI")
Set OInb = ONS.GetDefaultFolder(olFolderInbox)
Set OMail = OInb.Items
Set OFind = OMail.Find("[Subject] = ""*Sigma Report*""")

For Each OItem In OInb.Items.Restrict(OMail)

    If OItem.Attachments.Count <> 0 Then
        For Each OAtch In OItem.Attachments
            '~~> Download the attachment
            OAtch.SaveAsFile AttachmentPath & OAtch.Filename
            Exit For
        Next
    Else
        MsgBox "The mail doesn't have an attachment"
    End If
    Exit For
Next
End Sub

If I remove the .Restrict(OMail) part then the code works fine, but its always going to the 'else' condition even though the mail has an attachment present. Can someone please help me with this?

pnuts
  • 54,806
  • 9
  • 74
  • 122
RB49
  • 133
  • 1
  • 1
  • 12
  • Why not create a rule and then follow [THIS](http://stackoverflow.com/questions/11781320/download-attachment-from-outlook-and-open-in-excel/11782153#11782153) – Siddharth Rout Nov 27 '13 at 16:31
  • Thank You.. I used a part of that solution to extract the file successfully. – RB49 Nov 29 '13 at 12:53

1 Answers1

1

You are using Restrict incorrectly - the function takes a single parameter that is the string filter. Unfortunately, according the the msdn reference,

There is no way to perform a "contains" operation. For example, you cannot use Find or Restrict to search for items that have a particular word in the Subject field. Instead, you can use the AdvancedSearch method, or you can loop through all of the items in the folder and use the InStr function to perform a search within a field.

Blackhawk
  • 5,605
  • 3
  • 25
  • 53