Good afternoon,
I am trying to find a way to realize the following project:
When I receive an email with attachments and with a certain word in the subject, create a folder and download the attachments to that folder.
But so far I only got an error '424' - Object required on the line:
If TypeName(olMail) = "Mailterm" And myMail.Subject Like "*" & "prueba" & "*" And olMail.Attachments.Count > 0 Then
If I remove the part:
And myMail.Subject Like "*" & "prueba" & "*"
And run again that error disappears, however I get an error:
Run-time erro '13':
Type mismatch
Highlighting:
Next olMail
I am not an expert on VBA but if you could help me it would be appreciated.
Option Explicit
Sub Download_Attachments()
Dim ns As NameSpace
Dim olFolder_Inbox As Folder
Dim olMail As Object
Dim olAttachment As Attachment
Dim fso As Object
Dim File_Saved_Folder_Path As String
Dim sFolderName As String
sFolderName = Format(Now, "yyyyMMdd")
File_Saved_Folder_Path = "C:\Users\agonzalezp\Documents\prueba" & "\" & sFolderName
Set ns = GetNamespace("MAPI")
Set olFolder_Inbox = ns.GetDefaultFolder(olFolderInbox)
Set fso = CreateObject("Scripting.FileSystemObject")
For Each olMail In olFolder_Inbox.Items
If TypeName(olMail) = "MailItem" Then
If olMail.Subject Like "*" & "prueba" & "*" Then 'And olMail.Attachments.Count > 0
fso.CreateFolder (File_Saved_Folder_Path)
For Each olAttachment In olMail.Attachments
Select Case UCase(fso.GetExtensionName(olAttachment.FileName))
Case "XLSX", "XLSM"
olAttachment.SaveAsFile (File_Saved_Folder_Path)
End Select
Next olAttachment
End If
End If
Next olMail
Set olFolder_Inbox = Nothing
Set ns = Nothing
Set fso = Nothing
End Sub
Thanks to all of you for your collaboration and help.
Finally the code has been working as follows:
Public Sub Download_Attachments()
'If execute in excel, for sample.
'ADD 'Tools > References... Microsoft Outlook 16.0 Object Library
On Error GoTo Err_Control
Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.Attachment
Dim outItem As Object
Dim DestinationFolderName As String
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String, sFolderName As String
Dim FSO As Object
Dim SourceFileName As String, DestinFileName As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO = CreateObject("Scripting.Filesystemobject")
sFolderName = Format(Now, "yyyyMMdd")
sMailName = Format(Now, "dd/MM/yyyy")
DestinationFolderName = "C:\Users\agonzalezp\Documents\Automatizaciones"
saveFolder = DestinationFolderName & "\" & sFolderName
subjectFilter = "NUEVA" & " " & sMailName 'REPLACE WORD SUBJECT TO FIND
OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Set outApp = New Outlook.Application
OutlookOpened = True
End If
On Error GoTo Err_Control
If outApp Is Nothing Then
MsgBox "Cannot start Outlook.", vbExclamation
Exit Sub
End If
Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)
If Not outFolder Is Nothing Then
For Each outItem In outFolder.Items
If outItem.Class = Outlook.OlObjectClass.olMail Then
Set outMailItem = outItem
If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
For Each outAttachment In outMailItem.Attachments
If Dir(saveFolder, vbDirectory) = "" Then FSO.CreateFolder (saveFolder)
outAttachment.SaveAsFile saveFolder & " - " & outAttachment.fileName
Set outAttachment = Nothing
Next
End If
End If
Next
End If
SourceFileName = "C:\Users\agonzalezp\Documents\Automatizaciones\*.xlsx"
DestinFileName = saveFolder
FSO.MoveFile SourceFileName, DestinFileName
If OutlookOpened Then outApp.Quit
Set outApp = Nothing
Err_Control:
If Err.Number <> 0 Then
'MsgBox Err.Description
End If
End Sub
God afternow, Alejandro,
Try this, for me work, i try use split words your code but not good working, and find this solucion, I only insert create folder, respost is on site:
Save attachments to a folder and rename them David e jogold
Public Sub Download_Attachments()
'If execute in excel, for sample.
'ADD 'Tools > References... Microsoft Outlook 16.0 Object Library
On Error GoTo Err_Control
Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String, sFolderName As String
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
sFolderName = Format(Now, "yyyyMMdd")
saveFolder = "C:\DOCUMENTOS\Outlook_Anexos" & "\" & sFolderName 'REPLACE YOUR PATCH
If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"
subjectFilter = ("Aplicaciones") 'REPLACE WORD SUBJECT TO FIND
OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Set outApp = New Outlook.Application
OutlookOpened = True
End If
On Error GoTo Err_Control
If outApp Is Nothing Then
MsgBox "Cannot start Outlook.", vbExclamation
Exit Sub
End If
Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)
If Not outFolder Is Nothing Then
For Each outItem In outFolder.Items
If outItem.Class = Outlook.OlObjectClass.olMail Then
Set outMailItem = outItem
If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
For Each outAttachment In outMailItem.Attachments
If Dir(saveFolder, vbDirectory) = "" Then fso.CreateFolder (saveFolder)
outAttachment.SaveAsFile saveFolder & outAttachment.Filename
Set outAttachment = Nothing
Next
End If
End If
Next
End If
If OutlookOpened Then outApp.Quit
Set outApp = Nothing
Err_Control:
If Err.Number <> 0 Then
MsgBox Err.Description
End If
End Sub
Good afternoon Julio Gadioli Soares,
I have tried the code you have provided and it does work, but not as I expected.
I have managed to download the files without the permissions problem, but the files are not saved inside the folder that has been previously created, but outside.
Besides, their names have been changed.
Public Sub Download_Attachments()
'If execute in excel, for sample.
'ADD 'Tools > References... Microsoft Outlook 16.0 Object Library
On Error GoTo Err_Control
Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.NameSpace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.Attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String, sFolderName As String
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
sFolderName = Format(Now, "yyyyMMdd")
saveFolder = "C:\Users\agonzalezp\Documents\prueba" & "\" & sFolderName
subjectFilter = ("NUEVA") 'REPLACE WORD SUBJECT TO FIND
OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Set outApp = New Outlook.Application
OutlookOpened = True
End If
On Error GoTo Err_Control
If outApp Is Nothing Then
MsgBox "Cannot start Outlook.", vbExclamation
Exit Sub
End If
Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)
If Not outFolder Is Nothing Then
For Each outItem In outFolder.Items
If outItem.Class = Outlook.OlObjectClass.olMail Then
Set outMailItem = outItem
If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
For Each outAttachment In outMailItem.Attachments
If Dir(saveFolder, vbDirectory) = "" Then fso.CreateFolder (saveFolder)
outAttachment.SaveAsFile saveFolder & outAttachment.FileName
Set outAttachment = Nothing
Next
End If
End If
Next
End If
If OutlookOpened Then outApp.Quit
Set outApp = Nothing
Err_Control:
If Err.Number <> 0 Then
MsgBox Err.Description
End If
End Sub
Related
I am trying to create a macro which will save out all emails of a selected folder within outlook2010 to my desktop, the code below exports the emails to a specified location but any emails that have the same subject/timestamp are overwritten.
Can I get some advice on how to resolve this issue please.
Option Explicit
Dim StrSavePath As String
Sub SaveAllEmails_ProcessAllSubFolders()
Dim i As Long
Dim j As Long
Dim n As Long
Dim StrSubject As String
Dim StrName As String
Dim StrFile As String
Dim StrReceived As String
Dim StrFolder As String
Dim StrSaveFolder As String
Dim StrFolderPath As String
Dim iNameSpace As NameSpace
Dim myOlApp As Outlook.Application
Dim SubFolder As MAPIFolder
Dim mItem As MailItem
Dim FSO As Object
Dim ChosenFolder As Object
Dim Folders As New Collection
Dim EntryID As New Collection
Dim StoreID As New Collection
Set FSO = CreateObject("Scripting.FileSystemObject")
Set myOlApp = Outlook.Application
Set iNameSpace = myOlApp.GetNamespace("MAPI")
Set ChosenFolder = iNameSpace.PickFolder
If ChosenFolder Is Nothing Then
GoTo ExitSub:
End If
BrowseForFolder StrSavePath
Call GetFolder(Folders, EntryID, StoreID, ChosenFolder)
For i = 1 To Folders.Count
StrFolder = StripIllegalChar(Folders(i))
n = InStr(3, StrFolder, "\") + 1
StrFolder = Mid(StrFolder, n, 256)
StrFolderPath = StrSavePath & "\" & StrFolder & "\"
StrSaveFolder = Left(StrFolderPath, Len(StrFolderPath) - 1) & "\"
If Not FSO.FolderExists(StrFolderPath) Then
FSO.CreateFolder (StrFolderPath)
End If
Set SubFolder = myOlApp.Session.GetFolderFromID(EntryID(i), StoreID(i))
On Error Resume Next
For j = 1 To SubFolder.Items.Count
Set mItem = SubFolder.Items(j)
StrReceived = Format(mItem.ReceivedTime, "YYYYMMDD-hhmmss")
StrSubject = mItem.Subject
StrName = StripIllegalChar(StrSubject)
StrFile = StrSaveFolder & StrReceived & "_" & StrName & ".msg"
StrFile = Left(StrFile, 256)
mItem.SaveAs StrFile, 3
Next j
On Error GoTo 0
Next i
ExitSub:
End Sub
Function StripIllegalChar(StrInput)
Dim RegX As Object
Set RegX = CreateObject("vbscript.regexp")
RegX.Pattern = "[\" & Chr(34) & "\!\#\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
RegX.IgnoreCase = True
RegX.Global = True
StripIllegalChar = RegX.Replace(StrInput, "")
ExitFunction:
Set RegX = Nothing
End Function
Sub GetFolder(Folders As Collection, EntryID As Collection, StoreID As Collection, Fld As MAPIFolder)
Dim SubFolder As MAPIFolder
Folders.Add Fld.FolderPath
EntryID.Add Fld.EntryID
StoreID.Add Fld.StoreID
For Each SubFolder In Fld.Folders
GetFolder Folders, EntryID, StoreID, SubFolder
Next SubFolder
ExitSub:
Set SubFolder = Nothing
End Sub
Function BrowseForFolder(StrSavePath As String, Optional OpenAt As String) As String
Dim objShell As Object
Dim objFolder ' As Folder
Dim enviro
enviro = CStr(Environ("USERPROFILE"))
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Please choose a folder", 0, enviro & "\Desktop\")
StrSavePath = objFolder.self.Path
On Error Resume Next
On Error GoTo 0
ExitFunction:
Set objShell = Nothing
End Function
You can try function
Function FileExists(file as String) as Boolean
If Not Dir(file, vbDirectory) = vbNullString Then
Return True
Else
Return False
End If
End Function
This way you can loop and add a suffix to the filename
[your code]
Dim count as Integer = 0
While (FileExists(file))
count = count + 1
file = dir & filename & count & extension
End While
It will exit the loop as soon as it finds an available name
I get a generated report by Oracle web app every week. I got a macro working to extract that attachment report from my email, but for some reason the date filter doesn't do anything and it saves all the attachments with the email subject "VERIPRD: XXVER Veritiv Aging Report Main: PETROP01" (which is the subject of the report that I want, but I get this weekly, and I only need to extract the most current one)
Also, the report comes with a .out extension which can be opened up with Excel, but if I save that file within the macros as xlsx it gets corrupted.
So what I need is for this macro to actually filter by date, and Subject line (mentioned above), save the .out file as an Excel file titled "Aging Report" and, if there's already an "Aging Report" in destination folder, to replace that previous excel file and not prompt with a message asking me if I want to replace it.
Here's the code I have so far which I put in MS outlook:
Public Sub Extract_Outlook_Email_Attachments()
Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.NameSpace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.attachment
Dim outItem As Object
Dim saveFolder As String
saveFolder = "C:\Users\borjax01\Desktop\aging reports"
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String
If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\" & "Aging
Report.out"
inputDate = InputBox("Enter date to filter the email subject", "Extract
Outlook email attachments")
If inputDate = "" Then Exit Sub
InputDateFilter = inputDate
subjectFilter = ("VERIPRD : XXVER Veritiv Aging Report Main : PETROP01")
OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Set outApp = New Outlook.Application
OutlookOpened = True
End If
On Error GoTo 0
If outApp Is Nothing Then
MsgBox "Cannot start Outlook.", vbExclamation
Exit Sub
End If
Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.PickFolder
If Not outFolder Is Nothing Then
For Each outItem In outFolder.Items
If outItem.Class = Outlook.OlObjectClass.olMail Then
Set outMailItem = outItem
If outMailItem.Subject = subjectFilter Then
Debug.Print outMailItem.Subject
For Each outAttachment In outMailItem.Attachments
outAttachment.SaveAsFile saveFolder
Set outAttachment = Nothing
Next
End If
End If
Next
End If
If OutlookOpened Then outApp.Quit
Set outApp = Nothing
End Sub
A post might get answers more quickly if broken into multiple single questions as is expected in this Q & A.
Public Sub Extract_Outlook_Email_Attachments()
Dim OutlookOpened As Boolean
Dim OutApp As outlook.Application
Dim outNs As outlook.Namespace
Dim outFolder As outlook.MAPIFolder
Dim outAttachment As outlook.Attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As outlook.MailItem
Dim inputDate As String, subjectFilter As String
Dim fldrItems As Items
Dim resultItems As Items
Dim strFilter As String
saveFolder = "C:\Users\borjax01\Desktop\aging reports"
saveFolder = "H:\test2"
'If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\" & "Aging Report.out"
If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"
' subjectFilter = ("VERIPRD : XXVER Veritiv Aging Report Main : PETROP01")
' No "Re:" nor "Fw:"
subjectFilter = "VERIPRD : XXVER Veritiv Aging Report Main : PETROP01"
OutlookOpened = False
On Error Resume Next
Set OutApp = getObject(, "Outlook.Application")
If Err.number <> 0 Then
Set OutApp = New outlook.Application
OutlookOpened = True
End If
On Error GoTo 0
If OutApp Is Nothing Then
MsgBox "Cannot start Outlook.", vbExclamation
Exit Sub
End If
Set outNs = OutApp.GetNamespace("MAPI")
Set outFolder = outNs.PickFolder
If Not outFolder Is Nothing Then
Set fldrItems = outFolder.Items
strFilter = "[Subject] = '" & subjectFilter & "'"
Debug.Print strFilter
Set resultItems = fldrItems.Restrict(strFilter)
'Debug.Print resultItems.count
resultItems.Sort "[ReceivedTime]", True
For Each outItem In resultItems
If outItem.Class = outlook.OlObjectClass.olMail Then
Set outMailItem = outItem
If outMailItem.subject = subjectFilter Then
Debug.Print " outMailItem.subject: " & outMailItem.subject
Debug.Print " outMailItem.ReceivedTime: " & outMailItem.ReceivedTime
For Each outAttachment In outMailItem.Attachments
Debug.Print " outAttachment.DisplayName: " & outAttachment.DisplayName
If InStr(outAttachment.DisplayNamem, ".out") Then
outAttachment.SaveAsFile saveFolder & outAttachment.DisplayName
Exit Sub '<-- exit when most recent is saved
End If
Next
End If
End If
Next
End If
If OutlookOpened Then OutApp.Quit
Set OutApp = Nothing
End Sub
I have the following code to save emails from Outlook to a folder on the desktop.
I would like to name the files with the email subjects exactly the way they are in Outlook. I do not want to strip any characters.
I have played around with the macro but I can't fix it. Also would like to remove the time stamp date etc.
Option Explicit
Dim StrSavePath As String
Sub SaveAllEmails_ProcessAllSubFolders()
Dim i As Long
Dim j As Long
Dim n As Long
Dim StrSubject As String
Dim StrName As String
Dim StrFile As String
Dim StrReceived As String
Dim StrFolder As String
Dim StrSaveFolder As String
Dim StrFolderPath As String
Dim iNameSpace As NameSpace
Dim myOlApp As Outlook.Application
Dim SubFolder As MAPIFolder
Dim mItem As MailItem
Dim FSO As Object
Dim ChosenFolder As Object
Dim Folders As New Collection
Dim EntryID As New Collection
Dim StoreID As New Collection
Set FSO = CreateObject("Scripting.FileSystemObject")
Set myOlApp = Outlook.Application
Set iNameSpace = myOlApp.GetNamespace("MAPI")
Set ChosenFolder = iNameSpace.PickFolder
If ChosenFolder Is Nothing Then
'GoTo ExitSub:
End If
BrowseForFolder StrSavePath
Call GetFolder(Folders, EntryID, StoreID, ChosenFolder)
For i = 1 To Folders.Count
StrFolder = StripIllegalChar(Folders(i))
n = InStr(3, StrFolder, "\") + 1
StrFolder = Mid(StrFolder, n, 256)
StrFolderPath = StrSavePath & "\" & StrFolder & "\"
StrSaveFolder = Left(StrFolderPath, Len(StrFolderPath) - 1) & "\"
If Not FSO.FolderExists(StrFolderPath) Then
FSO.CreateFolder (StrFolderPath)
End If
Set SubFolder = myOlApp.Session.GetFolderFromID(EntryID(i), StoreID(i))
On Error Resume Next
For j = 1 To SubFolder.Items.Count
Set mItem = SubFolder.Items(j)
StrReceived = Format(mItem.ReceivedTime, "YYYYMMDD-hhmm")
StrSubject = mItem.Subject
StrName = StripIllegalChar(StrSubject)
StrFile = StrSaveFolder & StrReceived & "_" & StrName & ".msg"
StrFile = Left(StrFile, 256)
mItem.SaveAs StrFile, 3
Next j
On Error GoTo 0
Next i
ExitSub:
End Sub
Function StripIllegalChar(StrInput)
Dim RegX As Object
Set RegX = CreateObject("vbscript.regexp")
RegX.Pattern = "[\" & Chr(34) & "\!\#\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
RegX.IgnoreCase = True
RegX.Global = True
StripIllegalChar = RegX.Replace(StrInput, "")
ExitFunction:
Set RegX = Nothing
End Function
Sub GetFolder(Folders As Collection, EntryID As Collection, _
StoreID As Collection, Fld As MAPIFolder)
Dim SubFolder As MAPIFolder
Folders.Add Fld.FolderPath
EntryID.Add Fld.EntryID
StoreID.Add Fld.StoreID
For Each SubFolder In Fld.Folders
GetFolder Folders, EntryID, StoreID, SubFolder
Next SubFolder
ExitSub:
Set SubFolder = Nothing
End Sub
Function BrowseForFolder(StrSavePath As String, _
Optional OpenAt As String) As String
Dim objShell As Object
Dim objFolder ' As Folder
Dim enviro
enviro = CStr(Environ("USERPROFILE"))
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Please choose a folder", _
0, enviro & "C:\Temp\Folders")
StrSavePath = objFolder.self.Path
On Error Resume Next
On Error GoTo 0
ExitFunction:
Set objShell = Nothing
End Function
an alternative approach if you absolutely want to retain the original email unaltered is to create a new email message to yourself with the original email saved as an attachment. Save the new email with a corrected subject to avoid windows naming errors, it will retain a link to the unaltered original.
It's a few extra steps but you should be able to automate those if you insist on retaining the original email unaltered.
Its bad idea like Tim said, but if that is what you want to do then modify your j loop to something like this...
For j = 1 To SubFolder.Items.Count
Set mItem = SubFolder.Items(j)
StrSubject = mItem.Subject
StrSubject = StrSaveFolder & StrSubject & ".msg"
mItem.SaveAs StrSubject, 3
Next j
Good Luck...
I've got a rule + script setup in outlook. The rule looks for specific words in the email subject and then runs the script (defined in Modules) below. But it seems to be only working for my personal inbox and not a group inbox. The below is the code that works.
The lines in comments are me trying to work it out.
Public Sub saveAttachtoDisk(item As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "d:\temp\"
Dim objNS As Outlook.NameSpace
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
'Set objNS = olApp.GetNamespace("MAPI")
'Set myRecipient = objNS.CreateRecipient("XXXXXXX")
'myRecipient.Resolve
'set Items = objNS.GetSharedDefaultFolder(myRecipient, olFolderInbox).Items
'Dim itm As Outlook.MailItem
' If TypeName(item) = "MailItem" Then
' Set itm = item
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
Set objAtt = Nothing
Next
End Sub
This is how to go and read the email subject to launch further code :
Public Sub saveAttachtoDisk()
Dim olApp As Outlook.Application, _
oNS As Outlook.NameSpace, _
oFld As Outlook.Folder, _
oMails As Outlook.Items, _
oMail As Outlook.MailItem, _
oAtt As Outlook.Attachment, _
SaveFolder As String
SaveFolder = "d:\temp\"
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
Set oNS = olApp.GetNamespace("MAPI")
Set oFld = oNS.GetDefaultFolder(olFolderInbox)
Set oMails = oFld.Items
For Each oMail In oMails
If InStr(1, oMail.Subject, "Txt_to_Find") Then
'----Your code comes here
For Each oAtt In oMail.Attachments
oAtt.SaveAsFile SaveFolder & "\" & oAtt.DisplayName
Set oAtt = Nothing
Next oAtt
Else
End If
Next oMail
End Sub
I compiled and coded a macro for Outlook 2011. This macro for that it saves all the mails as word file.
The problem is that I couldn't close the dialog box automatically, I have so much signed message I couldn't solve this problem.
This is the message dialog:
And the code:
Option Explicit
Dim StrSavePath As String
Sub SaveAllEmails_ProcessAllSubFolders()
Dim i As Long
Dim j As Long
Dim n As Long
Dim strSubject As String
Dim StrName As String
Dim StrFile As String
Dim StrReceived As String
Dim StrFolder As String
Dim StrSaveFolder As String
Dim StrFolderPath As String
Dim iNameSpace As NameSpace
Dim myOlApp As Outlook.Application
Dim SubFolder As MAPIFolder
Dim mItem As Object
Dim docItem As Object
Dim FSO As Object
Dim ChosenFolder As Object
Dim Folders As New Collection
Dim EntryID As New Collection
Dim StoreID As New Collection
Dim checkIfDigitallySigned As Long
Set FSO = CreateObject("Scripting.FileSystemObject")
Set myOlApp = Outlook.Application
Dim OLIns As Outlook.Inspector
Set iNameSpace = myOlApp.GetNamespace("MAPI")
Set ChosenFolder = iNameSpace.PickFolder
Const olAlertsNone = 0
If ChosenFolder Is Nothing Then
GoTo ExitSub:
End If
Set docItem = Application.CreateItem(olMailItem)
docItem.BodyFormat = olFormatRichText
BrowseForFolder StrSavePath
Call GetFolder(Folders, EntryID, StoreID, ChosenFolder)
For i = 1 To Folders.Count
StrFolder = StripIllegalChar(Folders(i))
n = InStr(3, StrFolder, "\") + 1
StrFolder = Mid(StrFolder, n, 256)
StrFolderPath = StrSavePath & "\" & StrFolder & "\"
StrSaveFolder = Left(StrFolderPath, Len(StrFolderPath) - 1) & "\"
If Not FSO.FolderExists(StrFolderPath) Then
FSO.CreateFolder (StrFolderPath)
End If
Set SubFolder = myOlApp.Session.GetFolderFromID(EntryID(i), StoreID(i))
On Error Resume Next
For j = 1 To SubFolder.Items.Count
Set mItem = SubFolder.Items(j)
StrReceived = Format(mItem.ReceivedTime, "YYYYMMDD-hhmm")
strSubject = mItem.Subject
StrName = StripIllegalChar(strSubject)
StrFile = StrSaveFolder & StrReceived & "_" & StrName & ".doc"
StrFile = Left(StrFile, 256)
mItem.SaveAs StrFile, olRTF
Next j
On Error GoTo 0
Next i
ExitSub:
End Sub
Some utility functions used by the macro:
Function StripIllegalChar(StrInput)
Dim RegX As Object
Set RegX = CreateObject("vbscript.regexp")
RegX.Pattern = "[\" & Chr(34) & "\!\#\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
RegX.IgnoreCase = True
RegX.Global = True
StripIllegalChar = RegX.Replace(StrInput, "")
ExitFunction:
Set RegX = Nothing
End Function
Sub GetFolder(Folders As Collection, EntryID As Collection, StoreID As Collection, Fld As MAPIFolder)
Dim SubFolder As MAPIFolder
Folders.Add Fld.FolderPath
EntryID.Add Fld.EntryID
StoreID.Add Fld.StoreID
For Each SubFolder In Fld.Folders
GetFolder Folders, EntryID, StoreID, SubFolder
Next SubFolder
ExitSub:
Set SubFolder = Nothing
End Sub
Function BrowseForFolder(StrSavePath As String, Optional OpenAt As String) As String
Dim objShell As Object
Dim objFolder ' As Folder
Dim enviro
enviro = CStr(Environ("USERPROFILE"))
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Please choose a folder", 0, enviro & "\Documents\")
StrSavePath = objFolder.self.Path
On Error Resume Next
On Error GoTo 0
ExitFunction:
Set objShell = Nothing
End Function
There is no way to turn that prompt off. You can try to use Redemption (I am its author) to bypass the prompts. Note that signed/encrypted messages are processed separately since they need to be decrypted first.
set rSession = CreateObject("Redemption.RDOSession")
rSession.MAPIOBJECT = myOlApp.Session.MAPIOBJECT
set rFolder = rSession.GetRDOFolderFromOutlookObject(SubFolder)
ser rItems = rFolder.Items
For j = 1 To rItems.Count
Set mItem = rItems(j)
if TypeName(mItem) = "RDOEncryptedMessage" Then
'process encrypted/signed messages separately
mItem = mItem.GetDecryptedMessage
Enf If
StrReceived = Format(mItem.ReceivedTime, "YYYYMMDD-hhmm")
strSubject = mItem.Subject
StrName = StripIllegalChar(strSubject)
StrFile = StrSaveFolder & StrReceived & "_" & StrName & ".doc"
StrFile = Left(StrFile, 256)
mItem.SaveAs StrFile, olRTF
Next j