I have a folder of email files from which I'm trying to extract sender details using Dir. I need help in determining why the following code doesn't compile.
Sub UpdateReturns()
Dim fso As Object, fld As Object, olApp As Object, MailFile As Object, MsgDetail As Object
Dim stSearch As String, stPath As String, stFile As String, EmailFrom As String
stPath = "C:\010. Working Docs"
stSearch = "Approve"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(stPath)
Set olApp = CreateObject("Outlook.Application")
MailFile = Dir(stPath & "\*.msg")
Do While MailFile <> ""
Set MailFile = olApp.Session.OpenSharedItem(MailFile)
Set MsgDetail = Application.ActiveInspector.CurrentItem
EmailFrom = MsgDetail.SenderEmailAddress
Sheets("Settings").Cells(41, 4).Value = EmailFrom
'need to insert standard code to itterate down the list
'and match sender names to recipient names and votes ("Approve") etc
Loop
End Sub
I ended up working a way around it. I was just spinning my wheels with the outlook controls and I decided to work with something I know better, end result was i set it up to read from a save folder where the files are saved as text files, and i have a formula where the contents of the searched files drop to match them against sent emails.
Sub UpdateReturns()
Dim stPath As String, mailfile As String, Fname As String, Ename As String
Dim fso As Object, fld As Object
Dim i As Integer, count As Integer
Const strSearch = "From:"
stPath = "C:\010. Working Docs"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(stPath)
mailfile = Dir(stPath & "\Approve*.txt")
count = 0
Do While mailfile <> ""
count = count + 1
mailfile = Dir()
Loop
i = 0
mailfile = Dir(stPath & "\Approve*.txt")
Do While count >= 1
Open mailfile For Input As #1
Do Until EOF(1)
Line Input #1, textline
If InStr(textline, "From:") > 0 Then
Fname = mailfile
Ename = textline
End If
Loop
Close #1
Range("C" & (40 + count)).Value = Fname
Range("D" & (40 + count)).Value = Ename
mailfile = Dir()
count = count - 1
Loop
End Sub
Dir returns a string that represents the file name.
Sub UpdateReturns()
Dim fso As Object
Dim fld As Object
Dim olApp As Object
Dim MailFile As Object
Dim MailFileStr As String
Dim MailPathFileStr As String
Dim stPath As String
Dim EmailFrom As String
stPath = "C:\010. Working Docs"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(stPath)
Set olApp = CreateObject("Outlook.Application")
MailFileStr = Dir(stPath & "\*.msg")
' file name only, no path
Debug.Print "MailFileStr: " & MailFileStr
Do While MailFileStr <> ""
' path and file
MailPathFileStr = stPath & "\" & MailFileStr
Debug.Print vbCr & "MailPathFileStr: " & MailPathFileStr
Set MailFile = olApp.Session.OpenSharedItem(MailPathFileStr)
EmailFrom = MailFile.SenderEmailAddress
Debug.Print "EmailFrom: " & EmailFrom
Set MailFile = Nothing
MailFileStr = Dir ' Get next entry.
Loop
End Sub
Related
I'm trying read a stack of saved .msg emails in a folder on a shared drive.
I can't get into Outlook to search directly because my organisation won't allow me to because it's a department shared email.
The saved folder is my workaround. I need to pull the file path and the date that we received the email from these files and put them into Excel. I can't take the date that the file was created because otherwise that'll be the date that I saved the file.
I managed to get the file path, but as soon as I try to get the received time it breaks.
I tried setting the ReceivedTime as an object, a string, a date.
If I Dim it as an object it whines that it's object not set, if I set the ReceivedTime it does the same.
If I dim it as string I get error 91, if I remove the with statement it still gives me error 91.
If I delete ReceivedTime = MailItem.ReceivedTime it moves on to the next time it's mentioned and yells at me about that part.
I checked my spelling of Received all through the code and that's not it.
Here's my code at the moment. I edited the file location for privacy. It works without the received time part, so the file location isn't the problem.
Sub FileSearchAlt()
Worksheets("Sheet1").Activate
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Dim oMsg As Outlook.MailItem
Dim MailItem As Object
Dim ReceivedTime As String
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("C:\Users\THE LOCATION OF MY FILE")
With oMsg
ReceivedTime = MailItem.ReceivedTime
For Each oFile In oFolder.Files
Cells(i + 1, 1) = "C:\Users\THE LOCATION OF MY FILE" & oFile.Name
Cells(i + 1, 2) = MailItem.ReceivedTime
i = i + 1
Next oFile
End With
End Sub
It seems you are trying to get OOM properties from MSG files saved to the disk:
Cells(i + 1, 2) = MailItem.ReceivedTime
In that case you need to open such files in Outlook and then read the properties using the Outlook object model. The OpenSharedItem method allows to open a shared item from a specified path or URL. This method is used to open iCalendar appointment (.ics) files, vCard (.vcf) files, and Outlook message (.msg) files. The type of object returned by this method depends on the type of shared item opened.
Dir allows access to files in desktop folders.
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Sub FileSearchAlt()
Dim oApp As Object
Dim oNs As Object
Dim oFSO As Object
Dim desktopFolder As Object
Dim fPath As String
Dim fName As String
Dim fPathName As String
Dim i As Long
Dim oMsg As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
fPath = "C:\Users\THE LOCATION OF MY FILE"
'Dim enviro As String
'enviro = CStr(Environ("USERPROFILE"))
'fPath = enviro & "\Test\"
Debug.Print "fPath........: " & fPath
If Right(fPath, 1) <> "\" Then
fPath = fPath & "\"
Debug.Print "with backslash added"
Debug.Print "fPath........: " & fPath
End If
Set desktopFolder = oFSO.GetFolder(fPath)
Debug.Print "desktopFolder: " & desktopFolder.Name
Set oApp = CreateObject("Outlook.Application")
Set oNs = oApp.getnamespace("MAPI")
Debug.Print "Dir parameter: " & fPath & "*.msg"
fName = Dir(fPath & "*.msg")
Debug.Print "fName........: " & fName
Do While fName <> ""
fPathName = fPath & fName
Debug.Print "fPathName....: " & fPathName
Set oMsg = oNs.OpenSharedItem(fPathName)
With Worksheets("Sheet1")
.Cells(i + 1, 1) = fPathName
.Cells(i + 1, 2) = oMsg.receivedTime
i = i + 1
End With
fName = Dir
Debug.Print "fName........: " & fName
Loop
Debug.Print "Done."
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 am using this code to search within all relevant files in a folder.
How can I add the amount of times the string is found in each file so I can return that number? If it matters, I do know that the string I am searching will only be found once on each line of text.
I have tried a bunch of random things but I get only "1" returned, which I know is false.
Sub StringExistsInFile()
Dim theString As Variant
Dim path As String
Dim StrFile As String
Dim fso As New FileSystemObject
Dim file As TextStream
Dim line As String
theString = Userform1.TextBox1.Text
path = "P:\prg\"
StrFile = Dir(path & "*.dp")
Do While StrFile <> ""
Set file = fso.OpenTextFile(path & StrFile)
Do While Not file.AtEndOfLine
line = file.ReadLine
If InStr(1, line, theString, vbTextCompare) > 0 Then
Userform1.ListBox1.AddItem (StrFile)
Exit Do
End If
Loop
file.Close
Set file = Nothing
Set fso = Nothing
StrFile = Dir()
Loop
End Sub
Your code stopped at the first empty line within each file as you looped until AtEndOfLine.
Please try this:
Sub StringExistsInFile()
Dim theString As Variant
Dim path As String
Dim StrFile As String
Dim fso As New FileSystemObject
Dim file As TextStream
Dim line As String
Dim amount As Long
Dim theResult as String
theString = Userform1.TextBox1.Text
path = "P:\prg\"
StrFile = Dir(path & "*.dp")
Do While StrFile <> ""
Set file = fso.OpenTextFile(path & StrFile)
amount = 0
Do While Not file.AtEndOfStream
line = file.ReadLine
If InStr(1, line, theString, vbTextCompare) > 0 Then
amount = amount + 1
End If
Loop
If amount > 0 Then
Userform1.ListBox1.AddItem (StrFile & ": " & theString & " = " & amount)
End If
file.Close
Set file = Nothing
Set fso = Nothing
StrFile = Dir()
Loop
End Sub
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 - :-)
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