Search for folder by key in subject - vba

I need to move the incoming message to the related folder depending on a key in the subject of the message.
I developed a script for getting the key in the subject of new message. How can I search rest of messages by a key and retrieve related folder?
Sub CustomMailMessageRule(Item As Outlook.MailItem)
Dim strTicket, strSubject As String
Dim strFolder As String
strTicket = "None"
strSubject = Item.Subject
If InStr(1, strSubject, "#-") > 0 Then
strSubject = Mid(strSubject, InStr(strSubject, "#-") + 2)
If InStr(strSubject, " ") > 0 Then
strTicket = Left(strSubject, InStr(strSubject, " ") - 1)
End If
End If
the unknown part, search all folders by key and retrieve the related folder
strFolder = "???"
and finally, move the incoming message to the related folder by below code
If InStr(strFolder) > 0 Then
Item.Move Session.GetDefaultFolder(olFolderInbox).folders(strFolder)
MsgBox "Your New Message has been moved to related folder "
End Sub
I'm new in VBA.

This searches folders recursively for an item by subject.
Option Explicit
Sub CustomMailMessageRule(Item As mailItem)
Dim strSubject As String
Dim strDynamic As String
Dim strFilter As String
Dim originFolder As Folder
Dim startFolder As Folder
Dim uPrompt As String
strSubject = Item.subject
Set startFolder = Session.GetDefaultFolder(olFolderInbox)
' To reference any inbox not specifically the default inbox
'Set startFolder = Session.folders("email address").folders("Inbox")
Set originFolder = startFolder
' For testing the mail subject is "This is a test"
If InStr(1, strSubject, "This is") > 0 Then
' For testing the dynamically determined key is "a test"
strDynamic = "a test"
strFilter = "#SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " LIKE '%" & strDynamic & "%'"
Debug.Print strFilter
' Advanced search requires "Scope" to be specified so it appears
' not easy/possible to process every subfolder in the way described here
' https://stackoverflow.com/questions/43638711/outlook-macro-advanced-search
' This recursively processes every subfolder
processFolder originFolder, startFolder, strFilter, Item
uPrompt = "Mail with " & strDynamic & " in subject not found in subfolders of " & startFolder.Name
Debug.Print uPrompt
MsgBox uPrompt
End If
ExitRoutine:
Set startFolder = Nothing
End Sub
Private Sub processFolder(ByVal originFolder As Folder, ByVal oParent As Folder, strFilter As String, oIncomingMail As mailItem)
Dim oFolder As Folder
Dim oObj As Object
Dim filteredItems As items
Dim uResp As VbMsgBoxResult
Debug.Print oParent
If originFolder.EntryID <> oParent.EntryID Then
' This narrows the search.
' https://stackoverflow.com/questions/21549938/vba-search-in-outlook
Set filteredItems = oParent.items.Restrict(strFilter)
If filteredItems.count > 0 Then
Debug.Print oParent
Debug.Print "Mail found in " & oParent.Name
uResp = MsgBox(Prompt:="Move Message to folder: " & oParent.Name & "?", _
Buttons:=vbYesNoCancel)
If uResp = vbYes Then
oIncomingMail.move oParent
End
End If
If uResp = vbCancel Then End
End If
End If
If (oParent.folders.count > 0) Then
For Each oFolder In oParent.folders
processFolder originFolder, oFolder, strFilter, oIncomingMail
Next
End If
End Sub

Related

Downloading Outlook attachments

Is it possible to modify my code to download the most recent attachment from a certain sender rather than all the attachments in my inbox?
Private Sub GetAttachmentstttt()
Dim ns As NameSpace
Dim Inbox As Outlook.MAPIFolder
Dim Item As Object
Dim Atmt As Outlook.Attachment
Dim FileName As String
Set ns = GetNamespace("MAPI")
Set Inbox = ns.Folders("xx#gmail.com").Folders("Inbox")
If Inbox.Items.Count = 0 Then
MsgBox "There are no messages in the Inbox.", vbInformation, _
"Nothing Found"
Exit Sub
End If
For Each Item In Inbox.Items
For Each Atmt In Item.Attachments
If Atmt.Type = 1 And InStr(Atmt, "xls") > 0 Then
FileName = "C:\downloads" & Atmt.FileName
Atmt.SaveAsFile FileName
End If
Next Atmt
Next Item
End Sub
To restrict items by sender.
Option Explicit
Private Sub GetAttachments_SenderRestrict()
Dim inboxFolder As folder
Dim itm As Object
Dim itms As Items
Dim resItms As Items
Dim j As Long
Dim atmt As Attachment
Dim fileName As String
Dim srchSender As String
Dim strFilter As String
'Set inboxFolder = Session.folders("xx#gmail.com").folders("Inbox")
Set inboxFolder = Session.GetDefaultFolder(olFolderInbox)
Set itms = inboxFolder.Items
If itms.Count = 0 Then
MsgBox "There are no messages in the Inbox.", vbInformation, "Nothing Found"
Exit Sub
End If
Debug.Print vbCr & "itms.Count: " & itms.Count
srchSender = ActiveInspector.CurrentItem.senderName
strFilter = "[SenderName] = '" & srchSender & "'"
Debug.Print vbCr & strFilter
Set resItms = itms.Restrict(strFilter)
If resItms.Count = 0 Then
MsgBox "No " & srchSender & " email."
Exit Sub
End If
Debug.Print "resitms.Count: " & resItms.Count
'For Each itm In resItms
' Debug.Print itm.Subject
'Next itm
resItms.sort "[ReceivedTime]", True
For j = 1 To resItms.Count
Debug.Print resItms(j).ReceivedTime & ": " & resItms(j).Subject
Next j
' resItms(1) should be the most recent mail
Debug.Print vbCr & "resItms(1)"
Debug.Print resItms(1).ReceivedTime & ": " & resItms(1).Subject
For Each atmt In resItms(1).Attachments
If atmt.Type = 1 And InStr(atmt, "xls") > 0 Then
'Filename = "C:\downloads" & Atmt.Filename
fileName = "C:\downloads" & "\" & atmt.fileName
atmt.SaveAsFile fileName
End If
Next atmt
Debug.Print "Done."
End Sub

Saving Outlook Emails as ".msg" not as "File"

I've got this block of code to go through all the emails in my "Today" folder in Outlook, then save all the emails (.msg) to a folder named as the sender name.
Sometimes the files are saving with the file type "file".
How do I fix this to make sure the emails are saved as .msg files?
Sub SaveAttachments()
'https://www.fontstuff.com/outlook/oltut01.htm
'Declare Variables
Dim ns As NameSpace
Dim Inbox As Outlook.MAPIFolder
Dim Item As Object
Dim Atmt As Attachment
Dim Savefolder As String
Dim i As Integer
Set ns = GetNamespace("MAPI")
Set Inbox = ns.GetDefaultFolder(olFolderInbox).Folders("Today")
i = 0
'Stop script if there are no emails
If Inbox.Items.Count = 0 Then
MsgBox "There are no messages in the Inbox.", vbInformation, "Nothing Found"
Exit Sub
End If
'Display the number of emails
MsgBox Inbox.Items.Count, vbInformation, _
"Number of Emails?"
'Go through each email
For Each Item In Inbox.Items
'Create a path for the save folder
Savefolder = "C:\Users\work\Desktop\22_11_18\Test\" & Item.SenderName
'If the email has attachments, then create a folder
If Item.Attachments.Count > 0 Then
MkDir Savefolder
'If the folder already exists, skip to the next statement
On Error Resume Next
'Save the email as a .msg file
Item.SaveAs Savefolder & "\" & Item.Subject & ".msg"
End If
Next Item
End Sub
You can use subject if the characters in the subject are all valid.
Option Explicit
Private Sub SaveMail_ContainingAttachments_ValidSubject()
'Declare Variables
Dim ns As Namespace
Dim targetFolder As Folder
Dim itm As Object
Dim atmt As Attachment
Dim strSaveFolder As String
Dim validSubject As String
Set ns = GetNamespace("MAPI")
Set targetFolder = ns.GetDefaultFolder(olFolderInbox)
Set targetFolder = targetFolder.Folders("Today")
'Stop script if there are no emails
If targetFolder.Items.count = 0 Then
MsgBox "There are no messages in " & targetFolder & ".", vbInformation, "Nothing Found"
Exit Sub
End If
'Display the number of emails
MsgBox targetFolder.Items.count, vbInformation, "Number of Emails?"
'Go through each email
For Each itm In targetFolder.Items
'If the email has attachments, then create a folder
If itm.Attachments.count > 0 Then
'Create a path for the save folder
strSaveFolder = "C:\Users\work\Desktop\22_11_18\Test\" & itm.senderName
' Bypass error if the folder already exists
On Error Resume Next
MkDir strSaveFolder
' Discontinue error bypass as soon as the purpose is served
' Let unknown errors generate then fix them
On Error GoTo 0
' Replace or remove invalid characters
' Possible options "_" or " " or "" ....
validSubject = ReplaceIllegalChar(itm.subject, "_")
If validSubject <> itm.subject Then
Debug.Print itm.subject
Debug.Print validSubject
End If
'Save the email as a .msg file
itm.SaveAs strSaveFolder & "\" & validSubject & ".msg"
End If
Next itm
End Sub
Private Function ReplaceIllegalChar(strInput, strReplace)
Dim RegX As Object
Set RegX = CreateObject("vbscript.regexp")
RegX.Pattern = "[\" & Chr(34) & "\!\#\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
RegX.IgnoreCase = True
RegX.Global = True
' Replace with another string
ReplaceIllegalChar = RegX.Replace(strInput, strReplace)
ExitFunction:
Set RegX = Nothing
End Function

Rule that runs code to save attachments turns off

This Run a Script code to save attachments stops saving attachments because the rule turns off.
Public Sub SaveAttachmentsToDisk(MItem As Outlook.MailItem)
Dim oAttachment As Outlook.Attachment
Dim sSaveFolder As String
sSaveFolder = "C:\Users\andra.aeras\Documents\Test\"
For Each oAttachment In MItem.Attachments
If Right(oAttachment.FileName, 4) = "xlsx" Then
oAttachment.SaveAsFile sSaveFolder & oAttachment.DisplayName
End If
Next
End Sub
Is there a way to "enable" the rules or improve this code to run properly or run without using rules?
Try it like this.
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 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 = ""
If DestFolder = "" Then
Set wsh = CreateObject("WScript.Shell")
Set fs = CreateObject("Scripting.FileSystemObject")
MyDocPath = wsh.SpecialFolders.Item("mydocuments")
DestFolder = MyDocPath & "\" & Format(Now, "dd-mmm-yyyy hh-mm-ss")
If Not fs.FolderExists(DestFolder) Then
fs.CreateFolder DestFolder
End If
End If
If Right(DestFolder, 1) <> "\" Then
DestFolder = DestFolder & "\"
End If
' Check each message for attachments and extensions
For Each Item In SubFolder.Items
For Each Atmt In Item.Attachments
If LCase(Right(Atmt.FileName, Len(ExtString))) = LCase(ExtString) Then
FileName = DestFolder & Item.SenderName & " " & Atmt.FileName
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
' 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
Sub Test()
'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", "xls", ""
End Sub
Steps to follow:
1) Go to the VBA editor, Alt -F11
2) Tools>References in the Menu bar
3) Place a Checkmark before Microsoft Outlook ? Object Library
? is the Outlook version number
4) Insert>Module
5) Paste the code (two macros) in this module
6) Alt q to close the editor
7) Save the file

Can I drop items from Application.ActiveExplorer.Selection?

I take emails a user selects and then save them as text files, with the name of the text file as a portion of the subject line and then move that email to another folder in Outlook.
I managed to get all that working, but I also want the code to leave anything with two trip numbers in the subject line (Signified as Trip#XXXXXXXXX) alone and not move it, instead moving to the next selected email.
Exit Sub is a hard stop and I want to loop through the rest of the selection. Next oMail is something I'm only allowed one of and need at the end and GoTo that location skipping the rest of the code doesn't help.
Should I be using something other than For Each oMail In Application.ActiveExplorer.Selection?
The whole thing is as follows:
Sub SaveSentEmailAsParsedSubjectAndMove()
Dim oMail As Outlook.MailItem
'Folder path and file name
Dim strDesktop As String, strFileName As String, strFolderPath As String
'Four letters at the start of a trip/PAPS/PARS and the number itself
Dim strSCAC As String, strTripNumber As String
'Trip number counter
Dim strSubject As String, strSubject2 As String
Dim intTrips As Integer, intTrips1 As Integer, intTrips2 As Integer
'Duplicate checker
'Dim strTestStr As String, strTestPath As String
Dim strVersion As String, strVersionCheck As String
'File saved counter
Dim intFilesSaved As Integer
intFilesSaved = 0
'X carries the value for the file name, trying to save one higher in the event of a duplicate
Dim x As Integer
'Creates a text file on the desktop that will have all saved trip numbers written into it for the day.
Dim objFSO As Object
'Dim objFSO As New FileSystemObject
Dim objDailyLog As Object
'Dim objDailyLog As TextStream
Dim strTextFilePath As String
Dim strTextFilePathTest As String
'Constants for reading/writing to the daily log file - Appending adds data to the end.
'For Reading = 1
'For Writing = 2
'For Appending = 8
'Variables for the timers
'Daily log save time timer
Dim sngStart As Single, sngEnd As Single, sngElapsed As Single
Dim sngStart2 As Single, sngEnd2 As Single, sngElapsed2 As Single
If ActiveExplorer.Selection.Count = 0 Then
MsgBox "No files selected"
Exit Sub
End If
'Start timer
sngStart = Timer
sngStart2 = Timer
1
x = 1
'Set folder path - This will have to change to the J daily fax for release - J:\Fax Confirmations Daily
strDesktop = Environ("userprofile")
strFolderPath = strDesktop & "\Desktop\Test Folder\"
If Len(Dir(strFolderPath)) = 0 Then
MkDir strFolderPath
Else
End If
'strFolderPath = "J:\Fax Confirmations Daily\"
'Sets the path to create the record keeping text file in.
strTextFilePath = strDesktop & "\Desktop\" & Month(Date) & " " & Day(Date) & " Saved Faxes.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Len(Dir(strTextFilePath)) = 0 Then
'MsgBox "File does NOT exist"
Set objDailyLog = objFSO.CreateTextFile(strTextFilePath)
objDailyLog.Close
Else
'MsgBox "File already exists"
End If
'This will save all emails selected
For Each oMail In Application.ActiveExplorer.Selection
'Gets the subject line of the mail item
strSubject = oMail.Subject
'Gets the SCAC code from the subject line, the first four characters counting from left
strSCAC = strSubject
strSCAC = Left(strSCAC, 4)
'Counter. Stops process and returns error if there is more than one trip number detected.
strSubject2 = oMail.Subject
strSubject2 = Replace(strSubject2, "#", "")
intTrips1 = Len(strSubject)
intTrips2 = Len(strSubject2)
intTrips = intTrips1 - intTrips2
If intTrips > 1 Then
MsgBox "You have selected an email with more than one trip number in the subject. Please only select messages with a single trip number. Thanks.", 0, "Multiple Trip Numbers Detected"
GoTo 3
'Exit Sub
Else
'Gets the trip number, hereby defined as everything to the RIGHT of the # in the subject line
strTripNumber = strSubject
strTripNumber = Mid(strSubject, InStr(strSubject, "#") + 1)
'Set the File name
strVersion = ""
strFileName = strSCAC & strTripNumber & strVersion
2
'Test if file name exists. If yes, increase version number by 1 and try again.
'If no, save and continue processing.
If Len(Dir(strFolderPath & strFileName & " Sent" & strVersion & ".txt")) = 0 Then
'Save the text file with the completed file name to the previously defined folder
oMail.SaveAs strFolderPath & strFileName & " Sent" & strVersion & ".txt", olTXT
intFilesSaved = intFilesSaved + 1
'Open daily log file for addending (do not overwrite current data, merely add new lines to bottom)
Set objDailyLog = objFSO.OpenTextFile(strTextFilePath, 8, True)
objDailyLog.WriteLine (strFileName & " " & strVersion)
'Close the daily log text file
objDailyLog.Close
Else
'If the file already exists, increase the version counter by 1 and try again.
x = x + 1
strVersion = " " & x
GoTo 2
End If
End If
x = 1
'MoveToBackup
3
Next oMail
If intTrips > 1 Then
Set objDailyLog = objFSO.OpenTextFile(strTextFilePath, 8, True)
objDailyLog.WriteLine (Time)
objDailyLog.WriteLine "Saved in " & sngElapsed & " seconds"
objDailyLog.WriteLine "Error detected: Multiple trip numbers in subject line!"
objDailyLog.WriteBlankLines (1)
objDailyLog.Close
sngEnd2 = Timer
sngElapsed2 = Format(sngEnd2 - sngStart2, "Fixed")
MsgBox intFilesSaved & " file(s) saved successfully" & " in " & sngElapsed2 & " seconds", 0, "Files Saved"
intTrips = 0
Else
MoveToBackup
sngEnd = Timer
sngElapsed = Format(sngEnd - sngStart, "Fixed")
Set objDailyLog = objFSO.OpenTextFile(strTextFilePath, 8, True)
objDailyLog.WriteLine (Time)
objDailyLog.WriteLine "Saved in " & sngElapsed & " seconds"
objDailyLog.WriteBlankLines (1)
objDailyLog.Close
sngEnd2 = Timer
sngElapsed2 = Format(sngEnd2 - sngStart2, "Fixed")
MsgBox intFilesSaved & " file(s) saved successfully" & " in " & sngElapsed2 & " seconds", 0, "Files Saved"
End If
End Sub
'Outlook VB Macro to move selected mail item(s) to a target folder
Sub MoveToBackup()
On Error Resume Next
Dim ns As Outlook.NameSpace
Dim moveToFolder As Outlook.MAPIFolder
Dim objItem As Outlook.MailItem
Set ns = Application.GetNamespace("MAPI")
'Define path to the target folder - this was the original code,
Set moveToFolder = ns.GetDefaultFolder(olFolderSentMail).Folders("Backup")
If Application.ActiveExplorer.Selection.Count = 0 Then
MsgBox ("No item selected")
Exit Sub
End If
If moveToFolder Is Nothing Then
MsgBox "Target folder not found!", vbOKOnly + vbExclamation, "Move Macro Error"
End If
For Each objItem In Application.ActiveExplorer.Selection
If moveToFolder.DefaultItemType = olMailItem Then
If objItem.Class = olMail Then
objItem.Move moveToFolder
End If
End If
Next
Set objItem = Nothing
Set moveToFolder = Nothing
Set ns = Nothing
End Sub
You are already dropping items from the selection with
If intTrips > 1 Then
but later you move all mail in the selection.
You could move validated mail immediately.
Sub MoveValidatedMail()
Dim oMail As mailItem
'Four letters at the start of a trip/PAPS/PARS and the number itself
Dim strSCAC As String, strTripNumber As String
'Trip number counter
Dim strSubject As String, strSubject2 As String
Dim intTrips As Integer, intTrips1 As Integer, intTrips2 As Integer
'Move vaidated mail one at a time,
' within this code, rather than bulk move all mail
Dim ns As namespace
Dim moveToFolder As Folder
Dim objItem As Object
Set ns = GetNamespace("MAPI")
'Define path to the target folder
' If there is a typo or missing folder there would be an error.
' Bypass this one error only.
On Error Resume Next
Set moveToFolder = ns.GetDefaultFolder(olFolderSentMail).folders("Backup")
On Error GoTo 0
If moveToFolder Is Nothing Then
' Handle the bypassed error, if any
MsgBox "Target folder not found!", vbOKOnly + vbExclamation, "Move Macro Error"
Exit Sub
End If
If moveToFolder.DefaultItemType <> olMailItem Then
MsgBox "DefaultItemType <> olMailItem!", vbOKOnly + vbExclamation, "Move Macro Error"
Exit Sub
End If
If ActiveExplorer.Selection.count = 0 Then
MsgBox "No files selected"
Exit Sub
End If
For Each objItem In ActiveExplorer.Selection
If objItem.Class = olMail Then
Set oMail = objItem
'Gets the subject line of the mail item
strSubject = oMail.subject
'Gets the SCAC code from the subject line,
' the first four characters counting from left
strSCAC = strSubject
strSCAC = Left(strSCAC, 4)
'Counter. Stops process and returns error
' if there is more than one trip number detected.
strSubject2 = oMail.subject
strSubject2 = Replace(strSubject2, "#", "")
intTrips1 = Len(strSubject)
intTrips2 = Len(strSubject2)
intTrips = intTrips1 - intTrips2
If intTrips > 1 Then
MsgBox "Mail not moved " & oMail.subject
Else
' Move validated mail
objItem.move moveToFolder
MsgBox oMail.subject & " moved to " & moveToFolder
End If
End If
Set oMail = Nothing
Next objItem
Set oMail = Nothing
Set objItem = Nothing
Set moveToFolder = Nothing
Set ns = Nothing
End Sub
You could just use like
If oMail.Subject like "*TRIP*TRIP*" Then

Loop through outlook unread emails not working

I am having trouble getting this loop to work. Any advice?
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 MyDocPath As String
Dim i As Integer
Dim wsh As Object
Dim fs As Object
Dim InboxMsg As Object
On Error GoTo ThisMacro_err
Set ns = GetNamespace("MAPI")
Set Inbox = ns.GetDefaultFolder(olFolderInbox)
Set SubFolder = Inbox.Folders(OutlookFolderInInbox)
'To fix my issue I may have to change the loop to repeat the same number of
times as attachments
' Check subfolder for messages and exit of none found
' strFilter = "[Unread] = True"
' Set inboxItems =
ns.GetDefaultFolder(olFolderInbox).Folders(OutlookFolderInInbox).Items.Restrict(strFilter)
If SubFolder.UnReadItemCount = 0 Then
MsgBox "There are no New 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 = ""
If DestFolder = "" Then
Set wsh = CreateObject("WScript.Shell")
Set fs = CreateObject("Scripting.FileSystemObject")
MyDocPath = wsh.SpecialFolders.Item("mydocuments")
DestFolder = MyDocPath & "\" & Format(Now, "dd-mmm-yyyy hh-mm-ss")
If Not fs.FolderExists(DestFolder) Then
fs.CreateFolder DestFolder
End If
End If
If Right(DestFolder, 1) <> "\" Then
DestFolder = DestFolder & "\"
End If
' Check each message for attachments and extensions
strFilter = "[Unread] = True"
Set inboxItems =
ns.GetDefaultFolder(olFolderInbox).Folders(OutlookFolderInInbox).Items.Restrict(strFilter)
' For Each Item In inboxItems
For i = inboxItems.Count To 1 Step -1 'Iterates from the end backwards
Set InboxMsg = Inbox.Items(i)
'For Each Item In inboxItems
' For Each Atmt In inboxItems(I).Attachments
For Each Atmt In InboxMsg.Attachments
If LCase(Right(Atmt.FileName, Len(ExtString))) = LCase(ExtString)
Then
FileName = DestFolder & Format(Item.ReceivedTime, "yyyy-mmm-dd") & Atmt.FileName
Atmt.SaveAsFile FileName
End If
Item.UnRead = "False"
' inboxItems(I).UnRead = "False"
Next Atmt
' Item.UnRead = "false"
Next
' 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 Quick example, set filter for both UnRead & Items with Attachments
Option Explicit
Public Sub Example()
Dim olNs As Outlook.NameSpace
Dim Inbox As Outlook.MAPIFolder
Dim Items As Outlook.Items
Dim i As Long
Dim Filter As String
Set olNs = Application.GetNamespace("MAPI")
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Filter = "#SQL=" & Chr(34) & "urn:schemas:httpmail:hasattachment" & _
Chr(34) & "=1 AND " & _
Chr(34) & "urn:schemas:httpmail:read" & _
Chr(34) & "=0"
Set Items = Inbox.Items.Restrict(Filter)
For i = Items.Count To 1 Step -1
Debug.Print Items(i) 'Immediate Window
Next
End Sub