Reputation: 137
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?
Upvotes: 0
Views: 1472
Reputation: 6140
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.
Upvotes: 1