Reputation: 137
I have a folder created where all the mails are deposited based on a rule. The mail in the folder keeps accumulating everyday. I want to download the attachment from the latest mail in that folder. Currently, I am able to parse through all the files and download attachment from all the mails. How do I download only from the latest mail? Below is my code.
Sub FebAttachment_Click()
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
Dim strName As String
Dim strExt As String
Set oApp = GetObject(, "Outlook.application")
Set ONS = oApp.GetNamespace("MAPI")
Set OInb = ONS.Folders("Archive Folders").Folders("BIZOPS").Folders("2014.02")
Set OMail = OInb.Items
For Each OItem In OInb.Items
If OItem.Attachments.Count <> 0 Then
For Each OAtch In OItem.Attachments
strName = OAtch.Filename
strExt = Split(strName, ".z")(0)
OAtch.SaveAsFile AttachmentPath & OAtch.Filename
Exit For
Next
Else
MsgBox "The mail doesn't have an attachment"
End If
Next OItem
Upvotes: 0
Views: 1911
Reputation: 66266
Sort the items by the creation date (Items.Sort) in the descending order, then retrieve the first item in the collection.
Make sure your code operates on the same Items collection (retrieve OInb.Items once and cache it in a variable).
Upvotes: 1