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?