Historically I was using Excel and lotus notes to do this, company is transitioning thru to Outlook 2016 as it's standard email client.
We get daily reports to a mailbox from our Fridge units at multiple branches. each branch is a separate email but some of the attachments are named the same.
I used a script that copied the attachments from LN and it had a private function that in the processing of copying the attachments it would rename them if they had the same name.
I found a script here at stack overflow that I modified to save the attachments from Outlook into a Network folder. That works fine.
Here is the script
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
' Get the path to your My Documents folder
'strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
strFolderpath = "J:\Clayton\Logistics\Plantwatch\REPORTS\ZDumpSites\"
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
' Set the Attachment folder.
strFolderpath = strFolderpath '& "\Attachments\"
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection
' This code only strips attachments from mail items.
' If objMsg.class=olMail Then
' Get the Attachments collection of the item.
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
strDeletedFiles = ""
If lngCount > 0 Then
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
' Save attachment before deleting from item.
' Get the file name.
strFile = 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
' Delete the attachment.
'objAttachments.Item(i).Delete
'write the save as path to a string to add to the message
'check for html and use html tags in link
If objMsg.BodyFormat <> olFormatHTML Then
strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
Else
strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
strFile & "'>" & strFile & "</a>"
End If
'Use the MsgBox command to troubleshoot. Remove it from the final code.
'MsgBox strDeletedFiles
Next i
' Adds the filename string to the message body and save it
' Check for HTML body
If objMsg.BodyFormat <> olFormatHTML Then
objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
Else
objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
End If
objMsg.Save
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
I am trying to add this Function to this Script:
Private Function UniqueFileName(ByVal Fn As String) As String ' Rename same Name files.
Dim Fun As String ' Function return value
Dim Sp() As String ' Split file name
Dim Ext As Long ' file extension character count
Dim i As Integer ' file name index
Sp = Split(Fn, ".")
If UBound(Sp) Then Ext = Len(Sp(UBound(Sp))) + 1
Fun = stPath & Fn
Do While Len(Dir(Fun))
i = i + 1
Fun = stPath & Left(Fn, Len(Fn) - Ext) & _
"(" & CStr(i) & ")" & Right(Fn, Ext)
If i > 100 Then Exit Do
Loop
UniqueFileName = Fun
End Function
But search as I can I cannot see where this would fit or be added to the script.
How can I add this function to the excellent Script above to rename same named attachments?
I suspect I am missing something simple!
Change:
strFile = strFolderpath & strFile
to:
strFile = MakeUnique(strFolderpath & strFile)
Function:
Function MakeUnique(fPath As String) As String
Dim rv As String, fso, fName, fldr, ext, n
Set fso = CreateObject("scripting.filesystemobject")
rv = fPath
ext = "." & fso.getextensionname(fPath)
n = 2
Do While fso.fileexists(rv)
rv = Left(fPath, Len(fPath) - Len(ext)) & "(" & n & ")" & ext
n = n + 1
Loop
MakeUnique = rv
End Function
Try it like this
add the following to your variables
Dim nFileName As String
Dim Ext As String
then call the Function
For i = lngCount To 1 Step -1
' Save attachment before deleting from item.
' Get the file name.
strFile = objAttachments.Item(i).FileName
' ==============================================================
' ' // added
Ext = Right(strFile, _
Len(strFile) - InStrRev(strFile, Chr(46)))
nFileName = FileNameUnique(strFolderpath, strFile, Ext)
'================================================================
' Combine with the path to the Temp folder.
strFile = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFolderpath & nFileName ' < added
Here are you have two functions
'// Check if the file exists
Private Function FileExists(FullName As String) As Boolean
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(FullName) Then
FileExists = True
Else
FileExists = False
End If
Exit Function
End Function
'// If the same file name exist then add (1)
Private Function FileNameUnique(sPath As String, _
FileName As String, _
Ext As String) As String
Dim lngF As Long
Dim lngName As Long
lngF = 1
lngName = Len(FileName) - (Len(Ext) + 1)
FileName = Left(FileName, lngName)
Do While FileExists(sPath & FileName & Chr(46) & Ext) = True
FileName = Left(FileName, lngName) & " (" & lngF & ")"
lngF = lngF + 1
Loop
FileNameUnique = FileName & Chr(46) & Ext
Exit Function
End Function
Good Luck - :-)
Related
I want to fetch data from an email attachment in excel to a new excel and save the file in c drive in with a specific name. Below is the code which works fine. I want to add one more code which can copy data into new excel instead of renaming the same excel that comes as attachment in email.
Sub Test()
SaveEmailAttachmentsToFolder "Test", "xls", "C:\Users\fdmello\Desktop\Daily Reports\FL"
End Sub
Sub SaveEmailAttachmentsToFolder(OutlookFolderInInbox As String, _
ExtString As String, DestFolder As String)
Dim ns As NameSpace
Dim Inbox As MAPIFolder
Dim SubFolder As MAPIFolder
Dim Item As Object
Dim Atmt As Attachment
Dim FileName As String
Dim TempFileName As String
Dim MyDocPath As String
Dim I As Integer
Dim wsh As Object
Dim fs As Object
Dim FileNameString As String
On Error GoTo ThisMacro_err
Set ns = GetNamespace("MAPI")
Set Inbox = ns.GetDefaultFolder(olFolderInbox)
Set SubFolder = Inbox.Folders(OutlookFolderInInbox)
I = 0
' Check subfolder for messages and exit of none found
If SubFolder.Items.Count = 0 Then
MsgBox "There are no messages in this folder : " & OutlookFolderInInbox, _
vbInformation, "Nothing Found"
Set SubFolder = Nothing
Set Inbox = Nothing
Set ns = Nothing
Exit Sub
End If
If Right(DestFolder, 1) <> "\" Then
DestFolder = DestFolder & "\"
End If
For Each Item In SubFolder.Items
For Each Atmt In Item.Attachments
If LCase(Right(Atmt.FileName, Len(ExtString))) = LCase(ExtString) Then
FileNameString = "Data FL_MU_"
TempFileName = DestFolder & "Stagefile.xls"
FileName = DestFolder & FileNameString & Format(Item.ReceivedTime - 1, "ddmm") & ".xlsx"
Atmt.SaveAsFile FileName
I = I + 1
End If
Next Atmt
Next Item
Show this message when Finished
If I > 0 Then
MsgBox "You can find the files here : " _
& DestFolder, vbInformation, "Finished!"
Else
MsgBox "No attached files in your mail.", vbInformation, "Finished!"
End If
End Sub
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
Hope someone can help with this... thanks in advance!
I have numerous emails that are saved to the hard drive. Each email contains attachments with the same name as in the other emails. I have a working macro (thanks go Google) that will extract the attachments, save to a specific folder with a prefix to keep from overwriting. But what I really need for it to do is to rename the file based on the subject field. Or.. to at least be able to read some of the information from the subject line. Each email will have a set of numbers, followed by four characters within parenthesis. For example the subject will read... Successfully processed for your customer 123456789 (123A) accounts payable. I would like for the file to be saved as 123456789_123A and to add a _1 or _2 depending on how many files are in the email and to convert from XLSX to CSV.
We run this process biweekly and opening each email and doing "save as" is very time consuming as we are working with approximately 70 emails that each contain two attachments.
Below is the code that I am using. Any help would be most appreciated!!
Option Explicit
Const csOutlookIn As String = "In"
Const csOutlookOut As String = "Out"
Const csFilePrefix As String = "file"
Sub Extract_Emails_Demo2()
Application.ScreenUpdating = False
Dim sCurrentFolder As String
sCurrentFolder = ActiveWorkbook.Path & "\"
Dim FSO As Scripting.FileSystemObject
Set FSO = New Scripting.FileSystemObject
Dim fldrOutlookIn As Scripting.Folder
Set fldrOutlookIn = FSO.GetFolder(sCurrentFolder & csOutlookIn)
Dim oApp As Outlook.Application
Set oApp = New Outlook.Application
Dim oMail As Outlook.MailItem
Dim oAttach As Outlook.Attachment
Dim fileItem As Scripting.File
Dim sAttachName As String
Dim lcounter As Long
lcounter = 0
Dim scounter As String
For Each fileItem In fldrOutlookIn.Files
Set oMail = oApp.CreateItemFromTemplate(fileItem.Path)
For Each oAttach In oMail.Attachments
lcounter = lcounter + 1
scounter = Format(lcounter, "000")
sAttachName = oAttach.Filename
sAttachName = sCurrentFolder & csOutlookOut & "\" & scounter & "_" & sAttachName
oAttach.SaveAsFile sAttachName
Next oAttach
Set oMail = Nothing
Next fileItem
MsgBox "Finished Extrating Files"
Application.ScreenUpdating = True
End Sub
Thanks in advance!
Please, test the next adapted code. It will not take in consideration mails not having any attachment and will send a message containing the email subjects not containing two numbers. It uses two functions to build the necessary names to save the attachments, open them, save as csv and delete the xls* workbook:
Sub Extract_Emails_Demo2()
Const csOutlookIn As String = "In", csOutlookOut As String = "Out"
Const csFilePrefix As String = "file", prefixName As String = "abcdefg_"
Dim sCurrentFolder As String
sCurrentFolder = ActiveWorkbook.Path & "\"
Dim FSO As Scripting.FileSystemObject
Set FSO = New Scripting.FileSystemObject
Dim fldrOutlookIn As Scripting.Folder
Set fldrOutlookIn = FSO.GetFolder(sCurrentFolder & csOutlookIn)
Dim oApp As Outlook.Application
Set oApp = New Outlook.Application
Dim oMail As Outlook.MailItem
Dim oAttach As Outlook.Attachment
Dim fileItem As Scripting.file, sAttachName As String, scounter As String
Dim lcounter As Long, strSubject As String, arr, strNoPattern As String, strExt As String
For Each fileItem In fldrOutlookIn.files
Set oMail = oApp.CreateItemFromTemplate(fileItem.path)
strSubject = oMail.Subject: lcounter = 0
For Each oAttach In oMail.Attachments
'Debug.Print oAttach.DisplayName: Stop
lcounter = lcounter + 1
arr = extrAllNumb(strSubject) 'extract an array of found numbers in the subject text
sAttachName = buildName(arr, strSubject) 'build the name of the attachment to be saved
If sAttachName = "" Then 'if no any number found in the subject
strNoPattern = strNoPattern & fileItem & vbCrLf 'build the string of non conform Pattern files
GoTo LoopEnd 'skip the following code iteration lines
End If
strExt = Split(oAttach.DisplayName, ".")(UBound(Split(oAttach.DisplayName, ".")))
sAttachName = sAttachName & "_" & lcounter 'add the attachment number
sAttachName = sCurrentFolder & csOutlookOut & "\" & prefixName & sAttachName & "." & strExt
oAttach.SaveAsFile sAttachName 'save the attachment using the above built name
If strExt Like "xls*" Then 'saving excluding extension as pdf, doc, txt etc.
Dim wb As Workbook, CSVName As String
Application.ScreenUpdating = False 'some optimization for opening wb and process it
Set wb = Workbooks.Open(sAttachName) 'open the workbook
CSVName = Replace(sAttachName, "." & strExt, ".csv") 'build the csv name
wb.saveas CSVName, xlCSV 'save the wb as csv
wb.Close False 'close the wb without saving
Application.ScreenUpdating = True
Kill sAttachName 'delete the original attachment xls* file
End If
Next oAttach
LoopEnd:
Next fileItem
MsgBox "Finished Extrating Files"
If strNoPattern <> "" Then MsgBox "Wrong pattern files: " & vbCrLf & strNoPattern
End Sub
Function buildName(arr As Variant, strSubject As String) As String
Dim lngStart As Long, strChar As String
If Not IsArray(arr) Then buildName = "": Exit Function
If UBound(arr) >= 1 Then
lngStart = InStr(strSubject, arr(0)) + Len(CStr(arr(0)))
strChar = Mid(strSubject, InStr(lngStart, strSubject, arr(1)) + Len(CStr(arr(1))), 1)
'buildName = arr(0) & "_" & arr(1) & IIf(strChar = ")", "", strChar)
buildName = arr(1) & IIf(strChar = ")", "", strChar) & "_" & arr(0)
Else
buildName = arr(0)
End If
End Function
Private Function extrAllNumb(strVal As String) As Variant
Dim res As Object, El, arr, i As Long
With CreateObject("VBscript.RegExp")
.Pattern = "(\d{3,10})"
.Global = True
If .Test(strVal) Then
Set res = .Execute(strVal)
ReDim arr(res.count - 1)
For Each El In res
arr(i) = El: i = i + 1
Next
End If
End With
extrAllNumb = arr
End Function
If something not clear enough, please do not hesitate to ask for clarifications.
I want to save all attachments from a specific Outlook folder (MyFolder) to a desktop folder (Test). It seems to only work half of the time or not on all messages.
My first thought would be that the macro is quicker than Windows saving the files causing it to "skip" Outlook messages.
The code, partially from Ron de Bruin's website.
Option Explicit
Sub SaveAttachmentsFromMyFolder()
'Arg 1 = Folder name of folder inside your Inbox
'Arg 2 = File extension, "" is every file
'Arg 3 = Save folder, "C:\Users\Ron\test" or ""
' If you use "" it will create a date/time stamped folder for you in your "Documents" folder
' Note: If you use this "C:\Users\Ron\test" the folder must exist.
SaveEmailAttachmentsToFolder "MyFolder", "C:\Documents\Test"
End Sub
Sub SaveEmailAttachmentsToFolder(OutlookFolderInInbox As String, DestFolder As String)
Dim ns As NameSpace
Dim Inbox As MAPIFolder
Dim SubFolder As MAPIFolder
Dim Item As Object
Dim Atmt As Attachment
Dim FileName As String
Dim MyDocPath As String
Dim I As Integer
Dim wsh As Object
Dim fs As Object
On Error GoTo ThisMacro_err
Set ns = GetNamespace("MAPI")
Set Inbox = ns.GetDefaultFolder(olFolderInbox)
Set SubFolder = Inbox.Folders(OutlookFolderInInbox)
I = 0
' Check subfolder for messages and exit of none found
If SubFolder.Items.Count = 0 Then
MsgBox "There are no messages in this folder : " & OutlookFolderInInbox, _
vbInformation, "Nothing Found"
Set SubFolder = Nothing
Set Inbox = Nothing
Set ns = Nothing
Exit Sub
End If
'Create DestFolder if DestFolder = ""
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(DestFolder) Then
fs.CreateFolder DestFolder
End If
If Right(DestFolder, 1) <> "\" Then
DestFolder = DestFolder & "\"
End If
' Check each message for attachments and extensions
' Check flagstatus
For Each Item In SubFolder.Items
If Item.FlagStatus = olFlagComplete Then
Item.Delete
' build in a wait till file actually deleted?
Else
For Each Atmt In Item.Attachments
' missing code: extract date from file name, check if folder exists and create if not, save attachment in date-folder
FileName = DestFolder & Item.SenderName & " " & Atmt.FileName
Atmt.SaveAsFile FileName
' build in a wait till file actually saved?
I = I + 1
Next Atmt
Item.FlagStatus = olFlagComplete
Item.Save
' build in a wait till file actually saved?
End If
Next Item
' Show this message when Finished
If I > 0 Then
MsgBox "You can find the files here : " _
& DestFolder, vbInformation, "Finished!"
Else
MsgBox "No attached files in your mail.", vbInformation, "Finished!"
End If
' Clear memory
ThisMacro_exit:
Set SubFolder = Nothing
Set Inbox = Nothing
Set ns = Nothing
Set fs = Nothing
Set wsh = Nothing
Exit Sub
' Error information
ThisMacro_err:
MsgBox "An unexpected error has occurred." _
& vbCrLf & "Please note and report the following information." _
& vbCrLf & "Macro Name: SaveEmailAttachmentsToFolder" _
& vbCrLf & "Error Number: " & Err.Number _
& vbCrLf & "Error Description: " & Err.Description _
, vbCritical, "Error!"
Resume ThisMacro_exit
End Sub
Here is code I use to save attachments from selected e-mails. You should be able to alter the For loop to loop through a folder instead easily enough.
Public Sub SaveAttachmentsSelectedEmails()
Dim olItem As Outlook.MailItem
Dim olSelection As Outlook.Selection: Set olSelection = ActiveExplorer.Selection
Dim FilePath As String: FilePath = Environ("USERPROFILE") & "\Documents\Documents\Attachments"
If Dir(FilePath, vbDirectory) = "" Then
Debug.Print "Save folder does not exist"
Exit Sub
End If
For Each olItem In olSelection
SaveAttachments olItem, FilePath, RemoveAttachments:=False
Next olItem
End Sub
Private Function SaveAttachments(ByVal Item As Object, FilePath As String, _
Optional Prefix As String = "", _
Optional FileExtensions As String = "*", _
Optional Delimiter As String = ",", _
Optional RemoveAttachments As Boolean = False, _
Optional OverwriteFiles As Boolean = False) As Boolean
On Error GoTo ExitFunction
Dim i As Long, j As Long, FileName As String, Flag As Boolean
Dim Extensions() As String: Extensions = Split(FileExtensions, Delimiter)
If Right(FilePath, 1) <> "\" Then FilePath = FilePath & "\"
For j = LBound(Extensions) To UBound(Extensions)
With Item.Attachments
If .Count > 0 Then
For i = .Count To 1 Step -1
FileName = FilePath & Prefix & .Item(i).FileName
Flag = IIf(LCase(Right(FileName, Len(Extensions(j)))) = LCase(Extensions(j)), True, False)
Flag = IIf(FileExtensions = "*" Or Flag = True, True, False)
If Flag = True Then
If Dir(FileName) = "" Or OverwriteFiles = True Then
.Item(i).SaveAsFile FileName
Else
Debug.Print FileName & " already exists"
Flag = False
End If
End If
If RemoveAttachments = True And Dir(FileName) <> "" And Flag = True Then .Item(i).Delete
Next i
End If
End With
Next j
SaveAttachments = True
ExitFunction:
End Function
I created a function in Excel to save a specified attachment (Excel file) from a specified email to a file location.
My organisation has moved all of our files to Sharepoint. I tried to update my function using the SharePoint path, but it fails to save the attachment.
Function OpenEMailAttachment(Path As String, FileName As String, FindSubj As String, FindAttachName As String, SubFolder As Object)
Dim oOlAp As Object, oOlns As Object, oOlInb As Object
Dim oOlItm As Object, oOlAtch As Object
Dim wb As Workbook
Dim sSubj As String
'~~> Outlook Variables for email
' Other options for email properties are:
' eSender = oOlItm.SenderEmailAddress
' dtRecvd = oOlItm.ReceivedTime
' dtSent = oOlItm.CreationTime
' sMsg = oOlItm.Body
'~~> Get Outlook instance
Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)
'~~> Store the relevant info in the variables
For Each oOlItm In oOlInb.Items
sSubj = oOlItm.Subject
Debug.Print sSubj & "-->" & FindSubj
If sSubj Like FindSubj Then
Debug.Print "Opening attachment"
If oOlItm.Attachments.Count <> 0 Then
For Each oOlAtch In oOlItm.Attachments
'~~> Download the attachment
If oOlAtch.FileName Like FindAttachName Then
Debug.Print Path & FileName
oOlAtch.SaveAsFile Path & FileName
Debug.Print Path & oOlAtch.FileName
oOlItm.UnRead = False
DoEvents
oOlItm.Save
On Error Resume Next
oOlItm.Move SubFolder
On Error GoTo 0
End If
Next
End If
End If
Next
'~~> FilePath is the file that we earlier downloaded
Set wb = Workbooks.Open(Path & FileName)
OpenEMailAttachment = FileName
End Function
The path I specified is like https://MyOrg.sharepoint.com/teams/FolderName/
and the FileName like File%20Name.xlsx
Try this.
Sub copyFilesTo_Sharepoint()
Dim srcFolder As String
Dim dstFolder As String
' source path
srcFolder = "WriteYourSourcePathHere"
' destination path
dstFolder = "\\MyOrg.sharepoint.com\teams\FolderName"
' copies all Excel files starting with 'myfiles' with extension 'xslx'
Call fs_cpyFilesToFolder(srcFolder, dstFolder, "myfile*.xlsx")
End Sub
Sub fs_cpyFilesToFolder(srcPath As String, dstPath As String, Optional FileExt As String = "*.xlsx")
Dim fso As Object: Set fso = CreateObject("scripting.filesystemobject")
' checks if source path has a '\'
If Right(srcPath, 1) <> "\" Then
srcPath = srcPath & "\"
End If
' checks if source path exists
If fso.FolderExists(srcPath) = False Then
MsgBox srcPath & " doesn't exist"
Exit Sub
End If
' checks if destination path exists
If fso.FolderExists(dstPath) = False Then
MsgBox dstPath & " doesn't exist"
Exit Sub
End If
' copies files to sharepoint
fso.CopyFile Source:=srcPath & FileExt, Destination:=dstPath
End Sub
I'm using a script that opens an email and downloads its attachment. Right now I can either choose to download the most recent attachment on the most recent email:
Sub CTEmailAttDownload()
Const olFolderInbox As Integer = 6
'~~> Path for the attachment
Const AttachmentPath As String = "C:\TEMP\TestExcel"
Dim oOlAp As Object
Dim oOlns As Object
Dim oOlInb As Object
Dim oOlItm As Object
Dim oOlAtch As Object
Dim oOlResults As Object
Dim x As Long
Dim NewFileName As String
NewFileName = "Daily Tracker " & Format(Now, "dd-MM-yyyy")
'You can only have a single instance of Outlook, so if it's already open
'this will be the same as GetObject, otherwise it will open Outlook.
Set oOlAp = CreateObject("Outlook.Application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)
'No point searching the whole Inbox - just since yesterday.
Set oOlResults = oOlInb.Items.Restrict("[ReceivedTime]>'" & Format(Date - 1, "DDDDD HH:NN") & "'")
'If you have more than a single attachment they'll all overwrite each other.
'x will update the filename.
x = 1
For Each oOlItm In oOlResults
If oOlItm.Attachments.Count > 0 Then
For Each oOlAtch In oOlItm.Attachments
If GetExt(oOlAtch.FileName) = "xlsx" Then
oOlAtch.SaveAsFile AttachmentPath & "\" & NewFileName & ".xlsx"
End If
x = x + 1
Next oOlAtch
End If
Next oOlItm
End Sub
'----------------------------------------------------------------------
' GetExt
'
' Returns the extension of a file.
'----------------------------------------------------------------------
Public Function GetExt(FileName As String) As String
Dim mFSO As Object
Set mFSO = CreateObject("Scripting.FileSystemObject")
GetExt = mFSO.GetExtensionName(FileName)
End Function
By using '[Subject] =' I can download it by subject.
My question is, how can I put those two filters together so I can filter by Subject and ReceivedTime?
I tried binding them together with ,, &, + and so far I haven't been successful.
#SQL=(Subject LIKE '%blah%') AND (ReceivedTime > '01/02/2015')
It is a struggle to get the syntax for even one restrict. As indicated in the comment by Scott Holtzman, if you know each filter separately, you can filter twice.
Option Explicit
Sub CTEmailAttDownload()
Const olFolderInbox As Integer = 6
'~~> Path for the attachment
Const AttachmentPath As String = "C:\TEMP\TestExcel"
Dim oOlAp As Object
Dim oOlns As Object
Dim oOlInb As Object
Dim oOlItm As Object
Dim oOlAtch As Object
Dim oOlResults As Object
Dim oOlSubjectResults As Object
Dim strFilter As String
Dim i As Long
Dim x As Long
Dim NewFileName As String
NewFileName = "Daily Tracker " & format(Now, "dd-MM-yyyy")
'You can only have a single instance of Outlook, so if it's already open
'this will be the same as GetObject, otherwise it will open Outlook.
Set oOlAp = CreateObject("Outlook.Application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)
'No point searching the whole Inbox - just since yesterday.
Set oOlResults = oOlInb.Items.Restrict("[ReceivedTime]>'" & format(Date - 1, "DDDDD HH:NN") & "'")
strFilter = "#SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " like '%test%'"
Set oOlSubjectResults = oOlResults.Restrict(strFilter)
If oOlSubjectResults.count = 0 Then
Debug.Print "No emails found with applicable subject"
Else
'If you have more than a single attachment they'll all overwrite each other.
'x will update the filename.
x = 1
For i = 1 To oOlSubjectResults.count
Set oOlItm = oOlSubjectResults(i)
If oOlItm.Attachments.count > 0 Then
Debug.Print oOlItm.Subject
For Each oOlAtch In oOlItm.Attachments
Debug.Print oOlAtch.DisplayName
If GetExt(oOlAtch.FileName) = "xlsx" Then
oOlAtch.SaveAsFile AttachmentPath & "\" & NewFileName & ".xlsx"
End If
x = x + 1
Next oOlAtch
End If
Next i
End If
ExitRoutine:
Set oOlAp = Nothing
Set oOlns = Nothing
Set oOlInb = Nothing
Set oOlResults = Nothing
Set oOlSubjectResults = Nothing
End Sub