Hi Guys,
I have adapted the below code, which was given to me by Mancubus on this forum, and it works, issue now is that where there are more than 1 email with the same part description it opens and saves attachments from all of them.
I need to add a reference to only open the latest email by the received date, I have tried adapting the If Then statement to incorporate the ReceivedTime but this just errors. The original If Then statement is commented.
Can you please point me in the direction of adding in the latest received date to the code so that only the latest version of the email is opened.
Many Thanks
Private Sub Image21_Click()
Dim olMail As Object, olAtt As Object, pdat As Date
Dim strSaveToFolder As String, strPathAndFilename As String, Monday As String
pdat = Format(Now, "dd/mm/yyyy")
'Monday = DateAdd("ww", -1, pdat - (Weekday(pdat, vbMonday) - 8))
strSaveToFolder = "I:\H904 Supply Chain\Scott Atkinson\Dashboard\"
On Error GoTo errorhandler
With CreateObject("Outlook.Application")
For Each olMail In .GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
'If InStr(olMail.Subject, "Availability Measurement by SKU was executed at " & pdat) > 0 Then
If InStr(olMail.Subject, "Availability Measurement by SKU was executed at " & pdat) > 0 And _
"[ReceivedTime]" = pdat Then
If olMail.Attachments.Count > 0 Then
For Each olAtt In olMail.Attachments
Application.DisplayAlerts = False
strPathAndFilename = strSaveToFolder & Format(pdat, "dd.mm.yyyy") & " " & olAtt.Filename
olAtt.SaveAsFile strPathAndFilename
olMail.Save
Application.DisplayAlerts = True
Next olAtt
End If
End If
Next
On Error GoTo 0
End With
On Error Resume Next
Kill (strSaveToFolder & Format(pdat - 1, "dd.mm.yyyy") & " Availability Measurement by SKU.xlsx")
Kill (strSaveToFolder & Format(pdat - 3, "dd.mm.yyyy") & " Availability Measurement by SKU.xlsx")
On Error GoTo 0
On Error GoTo errorhandler
Application.DisplayAlerts = False
Workbooks.Open (strSaveToFolder & Format(pdat, "dd.mm.yyyy") & " Availability Measurement by SKU.xlsx")
Application.DisplayAlerts = True
On Error GoTo 0
Exit Sub
errorhandler:
MsgBox ("OOOPPPS it appears that this report has not yet been issued by IT, or you may not be authorised to view it.")
End Sub