I would like to setup a VBA to automatically download attachments from unread emails with the subject "Shipment MTD" in the sub-folder Inbox\Reports and save them to the following folder C:\My Documents\Daily Shipments
Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
Dim dtDate As Date
Dim sName As String
' Get the path to your My Documents folder
strFolderpath = "C:\My Documents\Daily Shipment"
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox).Folders("Reports")
Set myTasks = Fldr.Items
' Select unread items with required subject line
Set resultItems = myTasks.Restrict("[UnRead] = False AND [Subject] = ""Shipment MTD""")
' Get the collection of selected objects.
Set objSelection = resultItems
' The attachment folder needs to exist
' You can change this to another folder name of your choice
' Set the Attachment folder.
strFolderpath = strFolderpath & "\Daily Shipment\"
' Select attachements in messsage
Set objAttachments = objMsg.Attachments
' Check each selected item for attachments.
For Each resultItems In myTasks
lngCount = objAttachments.Count
If lngCount > 0 Then
dtDate = objMsg.SentOn
sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, vbUseSystem) & Format(dtDate, "hhnnss", vbUseSystemDayOfWeek, vbUseSystem) & "-" 'include DTS
For i = lngCount To 1 Step -1
' Get the file name.
strFile = sName & objAttachments.Item(i).FileName
' Combine with the path to the Temp folder.
strFile = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
Next i
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
I want to select only the unread emails in the reports folder. It seems that VBA is not selecting this correctly.
MyTasksorolApp) - ChronocidalItemsare inresultItems? (TryMsgBox resultItems.Count) Your DASL query will be looking for subjects that exactly match "Shipment MTD", no "Re: Shipment MTD" or "Shipment MTD - 2018-01-01" allowed. - Chronocidal