PDA

View Full Version : [SOLVED:] Code to read Outlook mail with specific subject



rolling_zep
08-16-2023, 01:27 PM
Hi,

I have posted this on Mr Excel too Code to read Outlook mail with specific subject | MrExcel Message Board (https://www.mrexcel.com/board/threads/code-to-read-outlook-mail-with-specific-subject.1243320/)
So, apologies for cross posting!
Admins, Please delete it, if this should not be done.

I have this working code which reads the mail and its attachment into a local folder. It is working well.
But a new requirement is to read the mails with subject containing the words, Customer ID 1000 - Smith, JOHN P, where the word Customer ID is always static but the number and name is dynamic.
I am not sure how to resolve this as my modified code does not read the mail which contains the word, Customer ID.


Private Sub cmdOutlook_Click()
Dim olApp As Object
Dim MYFOLDER As Object
Dim OlItems As Object
Dim olMail As Object
Dim x As Integer
Dim subject As String
Dim strFile As String
Dim strFolderpath As String
Dim objDestfolder As Object
Dim filterKeywords As String
Dim filter As String


Set olApp = GetObject(, "Outlook.Application")
If Err.Number = 429 Then
Set olApp = CreateObject("Outlook.Application")
End If

strFolderpath = "C:\Users\Testing"
'On Error Resume Next

' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"

Set MYFOLDER = olApp.GetNamespace("MAPI").Folders("Customer Mailbox").Folders("Inbox")


Set OlItems = MYFOLDER.Items

'Working code
'For Each OlMail In OlItems
'strFile = OlMail & ".XML"
'strFile = strFolderpath & strFile
'If OlMail.Attachments.Count > 0 Then
'For x = 1 To OlMail.Attachments.Count
'OlMail.Attachments.item(x).SaveAsFile strFile
'Next x
'End If
'Next

'Modified code
For i = OlItems.Items.Count To 1 Step -1
If TypeOf OlItems.Items(i) Is MailItem Then
Set olMail = OlItems.Items(i)
If InStr(olMail.subject, "Customer ID") > 0 Then ' how to use the Like condition here?
strFile = strFolderpath & strFile
If olMail.Attachments.Count > 0 Then
For x = 1 To olMail.Attachments.Count
olMail.Attachments.Item(x).SaveAsFile strFile
Next x
End If
End if
End if
Next




Set MYFOLDER = Nothing
Set olMail = Nothing
Set OlItems = Nothing
Set olApp = Nothing
End Sub

June7
08-16-2023, 01:46 PM
The InStr() condition should work. Have you step debugged? Is the subject pulled?

If olMail.Subject LIKE "*Customer ID*" Then

rolling_zep
08-17-2023, 06:13 AM
That code If olMail.subject Like "*Customer ID*" Then worked!

Thanks