Get the date of the oldest mail per category - excel

I have a macro to get the count of mails category-wise in Outlook.
Along with that I want the oldest mail date in a particular category. e.g. in the Red category there are 20 mails, so what is the date of the oldest mail in the Red category?
Sub CategoriesEmails()
Dim oFolder As MAPIFolder
Dim oDict As Object
Dim sStartDate As String
Dim sEndDate As String
Dim oItems As Outlook.Items
Dim sStr As String
Dim sMsg As String
Dim strFldr As String
Dim OutMail As Object
Dim xlApp As Object
On Error Resume Next
Set oFolder = Application.ActiveExplorer.CurrentFolder
Set oDict = CreateObject("Scripting.Dictionary")
sStartDate = Date - 365
sEndDate = Date
Set oItems = oFolder.Items.Restrict("[Received] >= '" & sStartDate & "' And [Received] <= '" & sEndDate & "'")
oItems.SetColumns ("Categories")
For Each aItem In oItems
sStr = aItem.Categories
If Not oDict.Exists(sStr) Then
oDict(sStr) = 0
End If
oDict(sStr) = CLng(oDict(sStr)) + 1
Next aItem
sMsg = ""
i = 0
strFldr = "C:\Users\singhab\Desktop\Macro\"
Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Visible = True
xlApp.Workbooks.Open strFldr & "Test.xlsx"
xlApp.Sheets("Sheet1").Select
For Each aKey In oDict.Keys
xlApp.Range("a1").Offset(i, 0).Value = sMsg & aKey
xlApp.Range("B1").Offset(i, 0).Value = oDict(aKey) & vbCrLf
i = i + 1
Next
xlApp.Save
Set oFolder = Nothing
End Sub
I get the output
What I want is

Work with Items.GetFirst Method (Outlook) which Returns An Object value that represents the first object contained by the collection
Code Example
Option Explicit
Public Sub Example()
Dim olNs As Outlook.NameSpace
Set olNs = Application.GetNamespace("MAPI")
Dim Inbox As Outlook.MAPIFolder
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Dim Items As Outlook.Items
Set Items = Inbox.Items.Restrict("[Categories] = 'Red Category'")
Dim Item As Object
Set Item = Items.GetFirst
Debug.Print Item.Subject & " " & Item.ReceivedTime
End Sub

Related

Reply to last email from specific sender in Excel

In Excel, I am looking up the email address of a person, and then I want to find the last email (send or received) and trigger a reply to this email. This reply is triggered by a button in Excel.
Dim a As Integer
Dim objOutlook As Object
Dim objMail As Object
Dim rngBody As Range
Dim rngAttach As Range
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
EmailStr = "sombody#gmail.com" (dummy replacement for my find the email adress in excel spreadsheet
then I would need to find emails to/from this address in my outlook, and then reply to the latest one.
What I did manage is start a new email to this person, but no idea how to find and reply
With objMail
.To = EmailStr
.CC = AMEmail
.Subject = TitleMail
.HTMLBody = BodyStr & Signature
.ReadReceiptRequested = True
.Display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
Set objOutlook = Nothing
Set objMail = Nothing
Set rngBody = Nothing
Set rngAttach = Nothing
Update: still struggling, but no more crashes for now. Wher I am stuck now it here:
Private Sub CommandButton2_Click()
Dim olApp As Object
Dim olNs As Object
Dim olFldr As Object
Dim olItems As Object
Dim olItemReply As Object
Dim i As Long
Dim emailStr As String
Dim filter As String
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(6) ' olFolderInbox
Debug.Print "olFldr: " & olFldr
emailStr = "sombody#gmail.com" '(email address in Excel spreadsheet)
Debug.Print "emailStr: " & emailStr
Set olItems = olFldr.Items
Debug.Print olItems.Count
'finds all 19 items in my inbox with msgbox(olItems.count)
filter = "[SenderEmailAddress] = '" & emailStr & "'"
Debug.Print filter
Set olItems = olFldr.Items.Restrict(filter)
Debug.Print olItems.Count
'finds 0 items now ??? why....
End sub
This demonstrates how to create a searchfolder of items received from an email address.
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Private Sub mailFromEmailAddress()
' Early binding
' Requires reference to Microsoft Outlook XX.X Object Library
Dim objOutlook As Outlook.Application
Dim strSearch As String
Dim strDASLFilter As String
Dim strDASLFilter_option As String
Dim strScope As String
Dim strScopeEdit As String
Dim objSearch As Search
Dim fldrNm As String
strSearch = "someone#internet.com"
Set objOutlook = CreateObject("Outlook.Application")
' create a searchfolder
Debug.Print
'strScope = "'Inbox', 'Deleted'"
strScope = "'Inbox'"
Debug.Print "strSearch...........: " & strSearch
' https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2007/aa579702(v=exchg.80)
' ***** use "fromemail" for "senderemailaddress" *****
strDASLFilter_option = "fromemail"
Debug.Print "strDASLFilter_option: " & strDASLFilter_option
'fldrNm = strDASLFilter_option & " " & strSearch
fldrNm = strSearch
Debug.Print "fldrNm..............: " & fldrNm
'strDASLFilter = "urn:schemas:httpmail:" & strDASLFilter_option & " LIKE '%" & strSearch & "%'"
strDASLFilter = "urn:schemas:httpmail:" & strDASLFilter_option & " LIKE '" & strSearch & "'"
Debug.Print "strDASLFilter.......: " & strDASLFilter
Debug.Print "strScope............: " & strScope
Set objSearch = objOutlook.AdvancedSearch(scope:=strScope, filter:=strDASLFilter, SearchSubFolders:=True, Tag:="SearchFolder")
Debug.Print fldrNm
'Save the search results to a searchfolder
objSearch.Save fldrNm
Debug.Print fldrNm & " saved."
' Question 2
' Reference the saved searchfolder
' https://stackoverflow.com/questions/55363286/how-do-you-set-a-folder-variable-for-a-search-folder
' Question 3
' Sort the collection of items in the searchfolder
' Reply to most recent and appropriate item
End Sub
To reply to most recently received mailitem in known folder.
Option Explicit' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Private Sub replyToSenderEmailAddress()
' Reply to most recently received mailitem in specified folder
' Late binding - reference to Outlook Object Library not required
Dim olApp As Object
Dim olNs As Object
Dim olFldr As Object
Dim olItems As Object
Dim olItemReply As Object
Dim i As Long
Dim emailStr As String
Dim filter As String
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(6) ' olFolderInbox
Debug.Print "olFldr: " & olFldr
emailStr = "sombody#gmail.com" '(email address in Excel spreadsheet)
Debug.Print "emailStr: " & emailStr
Set olItems = olFldr.Items
Debug.Print olItems.Count
filter = "[SenderEmailAddress] = '" & emailStr & "'"
Debug.Print filter
Set olItems = olFldr.Items.Restrict(filter)
Debug.Print olItems.Count
olItems.Sort "[ReceivedTime]", True
For i = 1 To olItems.Count
Debug.Print olItems(i).ReceivedTime
If olItems(i).Class = 43 Then
Set olItemReply = olItems(i).Reply
olItemReply.Display
Exit For
End If
Next
End Sub

Unable to find 'Type Mismatch Error" in VBA

Its works frist time when i am login to the system but for testing second time if i am going to run this code again it will gives me type mismatch error. can somebody help me on this.
Sub Saveattachment()
Application.DisplayAlerts = False
Dim ATMT As Outlook.Attachment
Dim OMAIL As Outlook.MailItem
Dim FOL As Outlook.Folder
Dim ONS As Outlook.Namespace
Dim OLOOK As Outlook.Application
Dim var As Date
Dim count As Long
count = 0
Dim name As String
Dim temp As Variant
Set OLOOK = New Outlook.Application
Set ONS = Outlook.GetNamespace("MAPI")
Set FOL = ONS.Folders("IM_DMBI").Folders("inbox")
Set OMAIL = OLOOK.CreateItem(olMailItem)
msgbox "Please remove old downloads, If already remove please ingore and press Ok to proceed", vbInformation
For Each OMAIL In FOL.items
For Each ATMAT In OMAIL.Attachments
var = Format(OMAIL.ReceivedTime, "MM/DD/YY")
name = Left(OMAIL.Subject, 3)
If name = "304" And var = Date And Err.Number = 13 Then
count = count + 1
ATMAT.SaveAsFile Sheet1.Cells(1, 1) & Application.PathSeparator & ATMAT.filename
End If
If var < Date Then
msgbox "Totlay:-" & count & " Files downloaded for today", vbInformation
Exit Sub
End If
Next
Next
Application.DisplayAlerts = True
End Sub
Screenshot of the error: https://i.stack.imgur.com/5dKPy.png
This helps you to ignore type mismatch error:
Sub GetAttachment()
Application.DisplayAlerts = False
Dim ATMT As Outlook.Attachment
Dim OMAIL As Outlook.MailItem
Dim FOL As Outlook.Folder
Dim ONS As Outlook.Namespace
Dim OLOOK As Outlook.Application
Dim var As Date
Dim count As Long
count = 0
Dim name As String
Dim temp As Variant
Set OLOOK = New Outlook.Application
Set ONS = Outlook.GetNamespace("MAPI")
Set FOL = ONS.Folders("IM_DMBI").Folders("inbox")
Set OMAIL = OLOOK.CreateItem(olMailItem)
'msgbox "Please remove old downloads, If already remove please ingore and press Ok to proceed", vbInformation
For Each OMAIL In FOL.items
On Error GoTo errorHandler
For Each ATMAT In OMAIL.Attachments
var = Format(OMAIL.ReceivedTime, "MM/DD/YY")
name = Left(OMAIL.Subject, 5)
If name = "304 r" And var = Date Then
count = count + 1
ATMAT.SaveAsFile Sheet1.Cells(1, 1) & Application.PathSeparator & ATMAT.filename
End If
If var < Date Then
'msgbox "Totlay:-" & count & " Files downloaded for today", vbInformation
Exit Sub
End If
Next
TypeMismatch:
Next
errorHandler:
If Err = 13 Then 'Type Mismatch
Resume TypeMismatch
End If
Application.DisplayAlerts = True
End Sub
There can be items other than mailitems in the inbox.
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Sub Saveattachment()
Application.DisplayAlerts = False
'Dim ATMT As outlook.Attachment
Dim ATMAT As outlook.Attachment
Dim oObjItem As Object 'Any type, there can never be a mismatch
Dim OMAIL As outlook.MailItem
Dim FOL As outlook.folder
Dim ONS As outlook.namespace
Dim OLOOK As outlook.Application
Dim var As Date
Dim count As Long
count = 0
Dim name As String
Dim temp As Variant
Set OLOOK = New outlook.Application
'Set ONS = outlook.GetNamespace("MAPI")
Set ONS = OLOOK.GetNamespace("MAPI")
Set FOL = ONS.folders("IM_DMBI").folders("inbox")
'Set OMAIL = OLOOK.CreateItem(olMailItem)
For Each oObjItem In FOL.Items ' any type of item
'For Each OMAIL In FOL.Items
' One of at least three ways to verify
If TypeName(oObjItem) = "MailItem" Then
' Now that you have a mailitem
Set OMAIL = oObjItem
For Each ATMAT In OMAIL.Attachments
Debug.Print "Attachment found."
Next
Else
Debug.Print "This would have been a type mismatch."
End If
Next
Application.DisplayAlerts = True
End Sub

Return individual sender of archived mail for a shared mailbox

I have written a macro which pulls the emails from the 'Sent Items' of a particular mailbox in Outlook. I am using .SenderName property to populate senders name in Excel.
The mailbox is shared by a team, and is labeled as 'ResearchHub'.
The macro is working when I pull out mails for recent days.
When I try to draw the archived mails, the .SenderName property pulls out the sender as 'ResearchHub', not the person who sent the mail.
MailItem.SentOnBehalfOfName property is pulling Research Hub as the sender and not the individual name.
I tried unarchiving the emails by opening them and copying them in a different folder, yet was unsuccessful in fetching the particular user as sender name.
Option Explicit
Sub test()
Dim Result As Object
Dim i As Integer
Dim dstart As Date
Dim dend As Date
Dim lower As String
Dim upper As String
Dim limit As String
dstart = InputBox("Enter Start Date in dd/mmm/yyyy format")
dend = InputBox("Enter End Date in dd/mmm/yyyy format")
lower = "[ReceivedTime] > '" & Format(dstart, "ddddd") & " 12:00 AM" & "'"
upper = "[ReceivedTime] > '" & Format(dend, "ddddd") & " 12:00 AM" & "'"
limit = lower & " AND " & upper
Dim objoutlook As outlook.Application
Dim oStore As outlook.Store
Dim onjNSpace As outlook.Namespace
Dim objFolder As outlook.Folder
Dim oAccount As Account
Set objoutlook = CreateObject("Outlook.Application")
Set objNSpace = objoutlook.GetNamespace("MAPI")
For Each objFolder In objNSpace.Folders
If objFolder.Name = "Research Hub" Then
Dim myfolder As outlook.Folder
Set myfolder = objFolder.Folders("Sent Items")
Dim objitem As Object
Dim irow As Integer
irow = 2
Set Result = myfolder.Items.Restrict(limit)
If Result.Couunt > 0 Then
For i = 1 To Result.Count
Cells(irow, 1) = objitem.SenderName
Cells(irow, 2) = objitem.To
Cells(irow, 3) = objitem.Subject
irow = irow + 1
Next i
End If
End If
Next
Set objoutlook = Nothing
Set objNSpace = Nothing
Set myfolder = Nothing
End Sub
Use the MailItem.SentOnBehalfOfName property instead.

Export contents of shared Outlook folder into Excel

I want to export mails from a shared mailbox into Excel.
Here is a code which is exporting mails from my default mailbox.
Sub ExportEmailsfromSpecificSender()
Dim objOutlook As Object
Dim objnSpace As Object
Dim objFolder As MAPIFolder
Dim objSubFolder As MAPIFolder
Dim objSubSubFolder As MAPIFolder
Dim EmailCount As Integer
' Dim dateStr As String
Dim myItems As Outlook.Items
Dim myFilterItems As Outlook.Items
' Dim dict As Object
' Dim msg As String
Dim excApp As Object
Dim excWkb As Object
Dim excWks As Object
' Dim intVersion As Integer
' Dim intMessages As Integer
Dim lngRow As Long
Dim strFilename As String
Dim objCategory As Category
Dim strFilter As String
Dim objEmails, objSpecificEmails As Outlook.Items
Dim objItem As Object
Dim strSpecificSender As String
Dim nRow As Integer
Dim strFilePath As String
Set objOutlook = CreateObject("Outlook.Application")
Set objnSpace = objOutlook.GetNamespace("MAPI")
Set excApp = CreateObject("Excel.Application")
Set excWkb = excApp.Workbooks.Add
On Error Resume Next
'Get the emails from a specific sender
'Set Items = GetFolderPath("PD Services\RetainPermanently\07 July 2018\").Items
Set objEmails = Application.Session.GetDefaultFolder(olFolderInbox).Items
strSpecificSender = InputBox("Input the name of the specific sender:", "Specify Sender")
strFilter = "[From] = '" & strSpecificSender & "'"
Set objSpecificEmails = objEmails.Restrict(strFilter)
Set objExcelApplication = CreateObject("Excel.Application")
Set objExcelWorkbook = objExcelApplication.Workbooks.Add
'Export the specific emails to worksheet
Set objExcelWorksheet = objExcelWorkbook.Worksheets(1)
With objExcelWorksheet
.Cells(1, 1) = "Subject"
.Cells(1, 2) = "Received"
.Cells(1, 3) = "Body"
End With
nRow = 2
For Each objItem In objSpecificEmails
With objExcelWorksheet
.Name = "From " & strSpecificSender
.Cells(nRow, 1) = objItem.Subject
.Cells(nRow, 2) = objItem.ReceivedTime
.Cells(nRow, 3) = objItem.Body
End With
nRow = nRow + 1
Next
objExcelWorksheet.Columns("A:E").AutoFit
'Save the Excel workbook
strFilePath = "H:\WINDOWS\system\Mitushi Documents " & strSpecificSender & ".xlsx"
objExcelWorkbook.Close True, strFilePath
'Notify you of the export complete
MsgBox ("Export Complete!")
End Sub
I am receiving a blank Excel file with only the column headers.
What should I modify here to get the emails from a shared mailbox called "PD Services" and a folder named "RetainPermanently"?
I'm not sure what a 'shared folder' is, but try the script below and see if you get the results you want.
Option Explicit On
Const fPath As String = "C:\Users\your_path_here\" 'The path to save the messages
Sub Download_Outlook_Mail_To_Excel()
Dim olApp As Object
Dim olFolder As Object
Dim olNS As Object
Dim xlBook As Workbook
Dim xlSheet As Worksheet
Dim NextRow As Long
Dim i As Long
Dim olItem As Object
Set xlBook = Workbooks.Add
Set xlSheet = xlBook.Sheets(1)
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err() <> 0 Then
Set olApp = CreateObject("Outlook.Application")
End If
On Error GoTo 0
With xlSheet
.Cells(1, 1) = "Sender"
.Cells(1, 2) = "Subject"
.Cells(1, 3) = "Date"
'.Cells(1, 4) = "Size"
.Cells(1, 5) = "EmailID"
.Cells(1, 6) = "Body"
CreateFolders fPath
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.PickFolder
For Each olItem In olFolder.Items
NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
If olItem.Class = 43 Then
.Cells(NextRow, 1) = olItem.Sender
.Cells(NextRow, 2) = olItem.Subject
.Cells(NextRow, 3) = olItem.SentOn
'.Cells(NextRow, 4) =
.Cells(NextRow, 5) = SaveMessage(olItem)
'.Cells(NextRow, 6) = olItem.Body 'Are you sure?
End If
Next olItem
End With
MsgBox "Outlook Mails Extracted to Excel"
lbl_Exit:
Set olApp = Nothing
Set olFolder = Nothing
Set olItem = Nothing
Set xlBook = Nothing
Set xlSheet = Nothing
Exit Sub
End Sub
Function SaveMessage(olItem As Object) As String
Dim Fname As String
Fname = Format(olItem.ReceivedTime, "yyyymmdd") & Chr(32) &
Format(olItem.ReceivedTime, "HH.MM") & Chr(32) & olItem.sendername & " - " & olItem.Subject
Fname = Replace(Fname, Chr(58) & Chr(41), "")
Fname = Replace(Fname, Chr(58) & Chr(40), "")
Fname = Replace(Fname, Chr(34), "-")
Fname = Replace(Fname, Chr(42), "-")
Fname = Replace(Fname, Chr(47), "-")
Fname = Replace(Fname, Chr(58), "-")
Fname = Replace(Fname, Chr(60), "-")
Fname = Replace(Fname, Chr(62), "-")
Fname = Replace(Fname, Chr(63), "-")
Fname = Replace(Fname, Chr(124), "-")
SaveMessage = SaveUnique(olItem, fPath, Fname)
lbl_Exit:
Exit Function
End Function
Private Function SaveUnique(oItem As Object,
strPath As String,
strFileName As String) As String
Dim lngF As Long
Dim lngName As Long
lngF = 1
lngName = Len(strFileName)
Do While FileExists(strPath & strFileName & ".msg") = True
strFileName = Left(strFileName, lngName) & "(" & lngF & ")"
lngF = lngF + 1
Loop
oItem.SaveAs strPath & strFileName & ".msg"
SaveUnique = strPath & strFileName & ".msg"
lbl_Exit:
Exit Function
End Function
Private Sub CreateFolders(strPath As String)
Dim strTempPath As String
Dim iPath As Long
Dim vPath As Variant
vPath = Split(strPath, "\")
strPath = vPath(0) & "\"
For iPath = 1 To UBound(vPath)
strPath = strPath & vPath(iPath) & "\"
If Not FolderExists(strPath) Then MkDir strPath
Next iPath
End Sub
Private Function FolderExists(ByVal PathName As String) As Boolean
Dim nAttr As Long
On Error GoTo NoFolder
nAttr = GetAttr(PathName)
If (nAttr And vbDirectory) = vbDirectory Then
FolderExists = True
End If
NoFolder:
End Function
Private Function FileExists(filespec) As Boolean
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(filespec) Then
FileExists = True
Else
FileExists = False
End If
lbl_Exit:
Exit Function
End Function

VBA to loop through email attachments and save based on given criteria

This is a follow up from a previous question (VBA to save attachments (based on defined criteria) from an email with multiple accounts)
Scenario: I have a code that loops through all e-mails in a certain outlook account, and saves the attachments to a selected folder. Previously, my problem was selecting which folder (and account) from where to extract the attachments (this was solved with a suggestion from the previous question).
Issue 1: The code is presenting a "Type Mismatch" error at the line:
Set olMailItem = olFolder.Items(i)
Issue 2: As stated in the question title, my main objective is to loop through all the attachments and save only those that have a given criteria (excel file, with one sheet name "ASK" and one named "BID"). More than a simple If to account for these criteria, I have to either download all files to "temp folder", to the selection and put the final resulting files in the output folder, or download everything to the final folder and delete the files that do not meet the criteria.
Problem: I can't seem to find the way to do either of those operations.
Question: How would one do that? And which of those two would be more efficient?
Code:
Sub email()
Application.ScreenUpdating = False
Dim olApp As New Outlook.Application
Dim olNameSpace As Object
Dim olMailItem As Outlook.MailItem
Dim olFolder As Object
Dim olFolderName As String
Dim olAtt As Outlook.Attachments
Dim strName As String
Dim sPath As String
Dim i As Long
Dim j As Integer
Dim olSubject As String
Dim olSender As String
Dim sh As Worksheet
Dim LastRow As Integer
'delete content except from row 1
ThisWorkbook.Worksheets("FileNames").Rows(2 & ":" & ThisWorkbook.Worksheets("FileNames").Rows.count).Delete
'set foldername and subject
olFolderName = ThisWorkbook.Worksheets("Control").Range("D10")
'olSubject = ThisWorkbook.Worksheets("Control").Range("D16")
olSender = ThisWorkbook.Worksheets("Control").Range("D16")
sPath = Application.FileDialog(msoFileDialogFolderPicker).Show
sPathstr = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
Set olNameSpace = olApp.GetNamespace("MAPI")
'check if folder is subfolder or not and choose olFolder accordingly
'Set olFolder = olNameSpace.GetDefaultFolder(olFolderInbox).Folders(olFolderName)
Set olFolder = olNameSpace.Folders("email#email.com").Folders("Inbox")
If (olFolder = "") Then
Set olFolder = olNameSpace.Folders("email#email.com").Folders("Inbox")
End If
'loop through mails
h = 2
For i = 1 To olFolder.Items.count
Set olMailItem = olFolder.Items(i)
'check if the search name is in the email subject
'If (InStr(1, olMailItem.Subject, olSubject, vbTextCompare) <> 0) Then
If (InStr(1, olMailItem.Sender, olSender, vbTextCompare) <> 0) Then
With olMailItem
strName = .Attachments.Item(j).DisplayName
'check if file already exists
If Not Dir(sPathstr & "\" & strName) = "" Then
.Attachments(j).SaveAsFile sPathstr & "\" & "(1)" & strName
ThisWorkbook.Worksheets("FileNames").Range("A" & h) = "(1)" & strName
Else
.Attachments(j).SaveAsFile sPathstr & "\" & strName
ThisWorkbook.Worksheets("FileNames").Range("A" & h) = strName
End If
h = h + 1
Next
End With
End If
Next
Application.ScreenUpdating = True
MsgBox "Download complete!", vbInformation + vbOKOnly, "Done"
End Sub
Issue 1 :
You probably have so meeting invites or something other than a regular mail in your folder.
Check the Class property of the Item to see if it's olMail
Issue 2 :
I'll go with error handling, here :
Save in temp folder with the appropriate name
Open the file
Try to get to the sheets
If there is an error, just close the file
If there is no error, save the file in destination folder
Full code :
Sub email_DGMS89()
Application.ScreenUpdating = False
Dim olApp As New Outlook.Application
Dim olNameSpace As Object
Dim olMailItem As Outlook.MailItem
Dim olFolder As Object
Dim olFolderName As String
Dim olAtt As Outlook.Attachments
Dim strName As String
Dim sPath As String
Dim i As Long
Dim j As Integer
Dim olSubject As String
Dim olSender As String
Dim sh As Worksheet
Dim LastRow As Integer
Dim TempFolder As String: TempFolder = VBA.Environ$("TEMP")
Dim wB As Excel.Workbook
'delete content except from row 1
ThisWorkbook.Worksheets("FileNames").Rows(2 & ":" & ThisWorkbook.Worksheets("FileNames").Rows.Count).Delete
'set foldername and subject
olFolderName = ThisWorkbook.Worksheets("Control").Range("D10")
'olSubject = ThisWorkbook.Worksheets("Control").Range("D16")
olSender = ThisWorkbook.Worksheets("Control").Range("D16")
sPath = Application.FileDialog(msoFileDialogFolderPicker).Show
sPathstr = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
Set olNameSpace = olApp.GetNamespace("MAPI")
'check if folder is subfolder or not and choose olFolder accordingly
'Set olFolder = olNameSpace.GetDefaultFolder(olFolderInbox).Folders(olFolderName)
Set olFolder = olNameSpace.Folders("email#email.com").Folders("Inbox")
If (olFolder = "") Then
Set olFolder = olNameSpace.Folders("email#email.com").Folders("Inbox")
End If
'loop through mails
h = 2
For i = 1 To olFolder.items.Count
'''Const olMail = 43 (&H2B)
If olFolder.items(i).Class <> olMail Then
Else
Set olMailItem = olFolder.items(i)
'check if the search name is in the email subject
'If (InStr(1, olMailItem.Subject, olSubject, vbTextCompare) <> 0) Then
If (InStr(1, olMailItem.Sender, olSender, vbTextCompare) <> 0) Then
With olMailItem
For j = 1 To .Attachments.Count
strName = .Attachments.Item(j).DisplayName
'check if file already exists
If Not Dir(sPathstr & "\" & strName) = vbNullString Then
strName = "(1)" & strName
Else
End If
'''Save in temp
.Attachments(j).SaveAsFile TempFolder & "\" & strName
ThisWorkbook.Worksheets("FileNames").Range("A" & h) = strName
'''Open file as read only
Set wB = workbooks.Open(TempFolder & "\" & strName, True)
DoEvents
'''Start error handling
On Error Resume Next
Set sh = wB.sheets("ASK")
Set sh = wB.sheets("BID")
If Err.Number <> 0 Then
'''Error = At least one sheet is not detected
Else
'''No error = both sheets found
.Attachments(j).SaveAsFile sPathstr & "\" & strName
End If
Err.Clear
Set sh = Nothing
wB.Close
On Error GoTo 0
h = h + 1
Next j
End With
End If
End If
Next i
Application.ScreenUpdating = True
MsgBox "Download complete!", vbInformation + vbOKOnly, "Done"
End Sub

Resources