I save incoming mail with an inbox rule and VBA code.
When there are multiple emails with the same name and also if the attachments have the same name they overwrite each other.
I need both the email and the attachments to loop through 1-10. There can be up to ten emails and attachments with the same names.
Sub SaveAsMsg(MyMail As MailItem)
' requires reference to Microsoft Scripting Runtime
' \Windows\System32\Scrrun.dll
' Also requires reference to Microsoft Word Object Library
Dim fso As FileSystemObject
Dim strSubject As String
Dim strSaveName As String
Dim blnOverwrite As Boolean
Dim strFolderPath As String
Dim looper As Integer
Dim strID As String
Dim olNS As Outlook.NameSpace
Dim oMail As Outlook.MailItem
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set oMail = olNS.GetItemFromID(strID)
'Get Sender email domain
sendEmailAddr = oMail.SenderEmailAddress
companyDomain = Right(sendEmailAddr, Len(sendEmailAddr) - InStr(sendEmailAddr, "#"))
' ### USER OPTIONS ###
blnOverwrite = False ' False = don't overwrite, True = do overwrite
'### THIS IS WHERE SAVE LOCATIONS ARE SET ###
'Currently only saves to yPath. Change the yPath variable to mPath in other areas of the script to enable the month folder.
bPath = "C:\email\" 'Defines the base path to save the email
cPath = bPath & companyDomain & "\" 'Adds company domain to base path
yPath = cPath & Format(Now(), "yyyy") & "\" 'Add year subfolder
mPath = yPath & Format(Now(), "MMMM") & "\" 'Add month subfolder
'### Path Validity ###
'Make sure base path exists
If Dir(bPath, vbDirectory) = vbNullString Then
MkDir bPath
End If
'Make sure company domain path exists
'If Dir(cPath, vbDirectory) = vbNullString Then
'MkDir cPath
'End If
'Make sure year path exists
'If Dir(yPath, vbDirectory) = vbNullString Then
'MkDir yPath
'End If
'Make sure month path exists (uncomment below lines to enable)
'If Dir(mPath, vbDirectory) = vbNullString Then
'MkDir mPath
'End If
'### Get Email subject & set name to be saved as ###
emailSubject = CleanFileName(oMail.Subject)
saveName = Format(oMail.ReceivedTime, "yyyymmdd") & "_" & emailSubject & ".txt"
Set fso = CreateObject("Scripting.FileSystemObject")
'### If don't overwrite is on then ###
If blnOverwrite = False Then
looper = 0
Do While fso.FileExists(yPath & saveName)
looper = looper + 1
saveName = Format(oMail.ReceivedTime, "yyyymmdd") & "_" & emailSubject & "_" & looper & ".txt"
Loop
Else '### If don't overwrite is off, delete the file ###
If fso.FileExists(yPath & saveName) Then
fso.DeleteFile yPath & saveName
End If
End If
'### Save MSG File ###
oMail.SaveAs bPath & saveName, olTXT
'### If Mail Attachments: clean file name, save into path ###
If oMail.Attachments.Count > 0 Then
For Each atmt In oMail.Attachments
atmtName = CleanFileName(atmt.FileName)
atmtSave = bPath & Format(oMail.ReceivedTime, "yyyymmdd") & "_" & atmtName
atmt.SaveAsFile atmtSave
Next
End If
Set oMail = Nothing
Set olNS = Nothing
Set fso = Nothing
End Sub
Function CleanFileName(strText As String) As String
Dim strStripChars As String
Dim intLen As Integer
Dim i As Integer
strStripChars = "/\[]:=," & Chr(34)
intLen = Len(strStripChars)
strText = Trim(strText)
For i = 1 To intLen
strText = Replace(strText, Mid(strStripChars, i, 1), "")
Next
CleanFileName = strText
End Function
Sub SaveAsPDF(MyMail As MailItem)
' requires reference to Microsoft Scripting Runtime
' \Windows\System32\Scrrun.dll
' Also requires reference to Microsoft Word Object Library
Dim fso As FileSystemObject
Dim strSubject As String
Dim strSaveName As String
Dim blnOverwrite As Boolean
Dim strFolderPath As String
Dim looper As Integer
Dim strID As String
Dim olNS As Outlook.NameSpace
Dim oMail As Outlook.MailItem
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set oMail = olNS.GetItemFromID(strID)
'Get Sender email domain
sendEmailAddr = oMail.SenderEmailAddress
companyDomain = Right(sendEmailAddr, Len(sendEmailAddr) - InStr(sendEmailAddr, "#"))
' ### USER OPTIONS ###
blnOverwrite = False ' False = don't overwrite, True = do overwrite
'### THIS IS WHERE SAVE LOCATIONS ARE SET ###
bPath = "C:\email\" 'Defines the base path to save the email
cPath = bPath & companyDomain & "\" 'Adds company domain to base path
yPath = cPath & Format(Now(), "yyyy") & "\" 'Add year subfolder
mPath = yPath & Format(Now(), "MMMM") & "\" 'Add month subfolder
'### Path Validity ###
If Dir(bPath, vbDirectory) = vbNullString Then
MkDir bPath
End If
'If Dir(cPath, vbDirectory) = vbNullString Then
' MkDir cPath
'End If
'If Dir(yPath, vbDirectory) = vbNullString Then
' MkDir yPath
'End If
'### Get Email subject & set name to be saved as ###
emailSubject = CleanFileName(oMail.Subject)
saveName = Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & emailSubject & ".mht"
Set fso = CreateObject("Scripting.FileSystemObject")
'### If don't overwrite is on then ###
If blnOverwrite = False Then
looper = 0
Do While fso.FileExists(bPath & saveName)
looper = looper + 1
saveName = Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & emailSubject & "_" & looper & ".mht"
pdfSave = Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & emailSubject & "_" & looper & ".pdf"
Loop
Else '### If don't overwrite is off, delete the file ###
If fso.FileExists(bPath & saveName) Then
fso.DeleteFile bPath & saveName
End If
End If
oMail.SaveAs bPath & saveName, olMHTML
pdfSave = bPath & Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & emailSubject & ".pdf"
'### Open Word to convert file to PDF ###
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(FileName:=bPath & saveName, Visible:=True)
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
pdfSave, ExportFormat:= _
wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=0, To:=0, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
wrdDoc.Close
wrdApp.Quit
'### Clean up files ###
With New FileSystemObject
If .FileExists(bPath & saveName) Then
.DeleteFile bPath & saveName
End If
End With
'### If Mail Attachments: clean file name, save into path ###
If oMail.Attachments.Count > 0 Then
For Each atmt In oMail.Attachments
atmtName = CleanFileName(atmt.FileName)
atmtSave = bPath & Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & atmtName
atmt.SaveAsFile atmtSave
Next
End If
Set oMail = Nothing
Set olNS = Nothing
Set fso = Nothing
End Sub
This works really well once you delete the if statements that delete the file. Thank you for the foundation.
I've modified the PDF portion of your code (for the better, I hope) and fixed an issue that the pdf filename would not increment if it existed already. I had to write a separate loop for the PDF because you basically stopped the loop with this line: pdfSave = bPath & Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & emailSubject & ".pdf" but I can't seem to get rid of that line without producing an error so made a new loop. Maybe someone can simplify that part for me.
I've also added a line to delete the .mht file only used to create the PDF and modified the filenames a bit:
Function CleanFileName(strText As String) As String
Dim strStripChars As String
Dim intLen As Integer
Dim i As Integer
strStripChars = "/\[]:=," & Chr(34)
intLen = Len(strStripChars)
strText = Trim(strText)
For i = 1 To intLen
strText = Replace(strText, Mid(strStripChars, i, 1), "")
Next
CleanFileName = strText
End Function
Sub SaveAsPDF(MyMail As MailItem)
' ### Requires reference to Microsoft Scripting Runtime ###
' ### Requires reference to Microsoft Word Object Library ###
' --- In VBE click TOOLS > REFERENCES and check the boxes for both of the above ---
Dim fso As FileSystemObject
Dim strSubject As String
Dim strSaveName As String
Dim blnOverwrite As Boolean
Dim strFolderPath As String
Dim sendEmailAddr As String
Dim senderName As String
Dim looper As Integer
Dim plooper As Integer
Dim strID As String
Dim olNS As Outlook.NameSpace
Dim oMail As Outlook.MailItem
Dim bPath, EmailSubject, saveName, pdfSave As String
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set oMail = olNS.GetItemFromID(strID)
' ### Get username portion of sender email address ###
sendEmailAddr = oMail.SenderEmailAddress
senderName = Left(sendEmailAddr, InStr(sendEmailAddr, "#") - 1)
' ### USER OPTIONS ###
blnOverwrite = False ' False = don't overwrite, True = do overwrite
' ### Path to save directory ###
bPath = "Z:\email\"
' ### Create Directory if it doesnt exist ###
If Dir(bPath, vbDirectory) = vbNullString Then
MkDir bPath
End If
' ### Get Email subject & set name to be saved as ###
emailSubject = CleanFileName(oMail.Subject)
saveName = Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & emailSubject & ".mht"
Set fso = CreateObject("Scripting.FileSystemObject")
' ### Increment filename if it already exists ###
If blnOverwrite = False Then
looper = 0
Do While fso.FileExists(bPath & saveName)
looper = looper + 1
saveName = Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & senderName & "_" & emailSubject & "_" & looper & ".mht"
Loop
Else
End If
' ### Save .mht file to create pdf from Word ###
oMail.SaveAs bPath & saveName, olMHTML
pdfSave = bPath & Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & senderName & "_" & emailSubject & ".pdf"
If fso.FileExists(pdfSave) Then
plooper = 0
Do While fso.FileExists(pdfSave)
plooper = plooper + 1
pdfSave = bPath & Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & senderName & "_" & emailSubject & "_" & plooper & ".pdf"
Loop
Else
End If
' ### Open Word to convert .mht file to PDF ###
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
' ### Open .mht file we just saved and export as PDF ###
Set wrdDoc = wrdApp.Documents.Open(FileName:=bPath & saveName, Visible:=True)
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
pdfSave, ExportFormat:= _
wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=0, To:=0, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
wrdDoc.Close
wrdApp.Quit
' ### Delete .mht file ###
Kill bPath & saveName
' ### Uncomment this section to save attachments ###
'If oMail.Attachments.Count > 0 Then
' For Each atmt In oMail.Attachments
' atmtName = CleanFileName(atmt.FileName)
' atmtSave = bPath & Format(oMail.ReceivedTime, "yyyy-mm-dd-hhmm") & "_" & atmtName
' atmt.SaveAsFile atmtSave
' Next
'End If
Set oMail = Nothing
Set olNS = Nothing
Set fso = Nothing
End Sub
I have noticed the following lines of code:
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set oMail = olNS.GetItemFromID(strID)
There is no need to get a new instance of the MailItem class. You can use the instance passed as a parameter.
If fso.FileExists(bPath & saveName) Then
fso.DeleteFile bPath & saveName
It looks like you delete existing files instead of saving a new ones with different names.
You may consider using the datetime (not only the date) marker when saving emails/attachments. Or you may check out whether such file exists on the disk already.
Related
i am trying to save a selected mail from outlook to a folder dynamically created with mail's subject name. The code ran successfully for one mail. if i select different mail and try to run the macro it is showing path not found error. My code is below:
Public Sub OpslaanMails()
Dim OlApp As Outlook.Application
Set OlApp = New Outlook.Application
Set OlApp = CreateObject("Outlook.Application")
Dim fName, sName As String
Dim oMail As Outlook.MailItem
fName = "F:\Test\inwards\"
Set oMail = OlApp.ActiveExplorer.Selection.Item(1)
sName = oMail.Subject
makeSelectionDir (sName)
sPath = fName & "\" & sName & "\"
oMail.SaveAs sPath & sName & ".msg", olMsg
For Each oAttach In oMail.Attachments
oAttach.SaveAsFile sPath & oAttach.FileName
Set oAttach = Nothing
Next
End Sub
Sub makeSelectionDir(sName As String)
Dim fName, sPath As String
fName = "F:\Test\inwards\"
sPath = fName & sName
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(sName) Then .CreateFolder sPath 'error is in this line
End With
End Sub
Make sure sName does not contain any characters illegal in a file name, such as ":".
I used your idea and changed two or three things to make it more robust.
Put this in a module in Outlook VBA Editor and run, having selected an email.
I also added the time and date at the beginning of the folder and email file names.
I left the part about saving file attachements but know that they are already embedded in the .msg file.
Const ILLEGAL_CHARACTERS = Array("*", "/", "\", "?", """", "<", ">", ":", "|")
Sub SaveEmailToFile()
Dim oMail As MailItem
Dim sPath As String
Dim sObj As String
Dim oAttach As Attachment
'Select email and process subject
If ActiveExplorer.Selection.Count = 0 Then
MsgBox "No emails are selected."
Exit Sub
End If
Set oMail = ActiveExplorer.Selection.Item(1)
With oMail
sObj = oMail.Subject
'Remove illegal characters from email subject
If sObj = "" Then
sObj = "No Object"
Else
For Each s In ILLEGAL_CHARACTERS
sObj = Replace(sObj, s, "")
Next s
End If
'Get date and time string from email received timestamp
dateStr = Year(.ReceivedTime) & "_" & _
Month(.ReceivedTime) & "_" & _
Day(.ReceivedTime) & " " & _
Hour(.ReceivedTime) & " " & _
Minute(.ReceivedTime) & " " & _
Second(.ReceivedTime) & " "
End With
sPath = "C:\Someplace\" & dateStr & sObj & "\"
'Create folder
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(sPath) Then .CreateFolder sPath
End With
'Save email and attachements
oMail.SaveAs sPath & oMail.Subject & ".msg", olMSG
For Each oAttach In oMail.Attachments
oAttach.SaveAsFile sPath & oAttach.FileName
Next oAttach
End Sub
I could only recreate the error
path not found
if fName was not valid.
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Public Sub OpslaanMails()
Dim fName As String
Dim sName As String
Dim sPath As String
Dim oMail As MailItem
Dim oAttach As Attachment
fName = "F:\Test\inwards\"
Debug.Print "fName: " & fName
Set oMail = ActiveExplorer.Selection.Item(1)
sName = oMail.subject
Debug.Print "sName: " & sName
' Double slash accepted by Windows but not by some programmers
'If Right(fName, 1) = "\" Then
' fName = Left(fName, Len(fName) - 1)
' Debug.Print
' Debug.Print "fName: " & fName
'End If
' Double slash after fName preferable to no slash
sPath = fName & "\" & sName & "\"
Debug.Print "sPath: " & sPath
makeSelectionDir fName, sPath
' Possible illegal characters in sName not addressed.
' Do not test with replies nor forwards,
' the : in the subject is not a legal character.
oMail.SaveAs sPath & sName & ".msg", olMsg
For Each oAttach In oMail.Attachments
oAttach.SaveAsFile sPath & oAttach.FileName
Set oAttach = Nothing
Next
End Sub
Sub makeSelectionDir(fName As String, sPath As String)
With CreateObject("Scripting.FileSystemObject")
' Test for fName
' Otherwise there is file not found error in the create
If .FolderExists(fName) Then
' if subfolder does not exist create it
If Not .FolderExists(sPath) Then
.createFolder sPath
End If
Else
Debug.Print
Debug.Print "Folder " & fName & " does not exist."
'MsgBox "Folder " & fName & " does not exist."
End
End If
End With
End Sub
Inconsistency of sName vs sPath has been addressed in
If Not .FolderExists(sName) Then .CreateFolder sPath
Here's what I'm trying to do.
We occasionally get emails that has the following info:
Name: In the subject line between ( and -
DoB: In the e-mail Body:
date for receving e-mail: In the mail item itself.
I can get the name and date easily enough, but the DoB is behaving strange when I try to add it to the file name, it'll usually discard the name I've extracted.
This is the code I'm using:
Sub SaveAsPDF(MyMail As MailItem)
' ### Requires reference to Microsoft Scripting Runtime ###
' ### Requires reference to Microsoft Word Object Library ###
' --- In VBE click TOOLS > REFERENCES and check the boxes for both of the above ---
Dim fso As FileSystemObject
Dim strSubject As String
Dim strSaveName As String
Dim blnOverwrite As Boolean
Dim strFolderPath As String
Dim sendEmailAddr As String
Dim clientName As String
Dim openPos1 As Integer
Dim closePos1 As Integer
Dim openPos2 As Integer
Dim closePos2 As Integer
Dim senderName As String
Dim looper As Integer
Dim plooper As Integer
Dim strID As String
Dim olNS As Outlook.NameSpace
Dim oMail As Outlook.MailItem
Dim bDay As String
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set oMail = olNS.GetItemFromID(strID)
emailSubject = CleanFileName(oMail.Subject)
' ### Get username portion of sender email address ###
sendEmailAddr = oMail.SenderEmailAddress
senderName = Left(sendEmailAddr, InStr(sendEmailAddr, "#") - 1)
' ### Get Client birthday ###
openPos1 = InStr(oMail.Body, "DOB:")
closePos1 = InStr(oMail.Body, "TLF:")
bDay = Mid(oMail.Body, openPos1 + 12, closePos1 - openPos1 - 12)
' ### USER OPTIONS ###
blnOverwrite = False ' False = don't overwrite, True = do overwrite
' ### Path to save directory ###
bPath = "C:\Email test\"
' ### Create Directory if it doesnt exist ###
If Dir(bPath, vbDirectory) = vbNullString Then
MkDir bPath
End If
' ### Get Email subject & set name to be saved as ###
saveName = clientName & " " & Format(oMail.ReceivedTime, "dd-mm-yyyy") & ".mht"
Set fso = CreateObject("Scripting.FileSystemObject")
' ### Get the client name from the email subject ###
openPos2 = InStr(emailSubject, "(")
closePos2 = InStr(emailSubject, "-")
clientName = Mid(emailSubject, openPos2 + 1, closePos2 - openPos2 - 1)
' ### Increment filename if it already exists ###
If blnOverwrite = False Then
looper = 0
Do While fso.FileExists(bPath & saveName)
looper = looper + 1
saveName = clientName & " " & Format(oMail.ReceivedTime, "dd-mm-yyyy") & " " & looper & ".mht"
Loop
Else
End If
' ### Save .mht file to create pdf from Word ###
oMail.SaveAs bPath & saveName, olMHTML
pdfSave = bPath & clientName & " " & Format(oMail.ReceivedTime, "dd-mm-yyyy") & ".pdf"
If fso.FileExists(pdfSave) Then
plooper = 0
Do While fso.FileExists(pdfSave)
plooper = plooper + 1
pdfSave = bPath & clientName & " " & Format(oMail.ReceivedTime, "dd-mm-yyyy") & " " & plooper & ".pdf"
Loop
Else
End If
' ### Open Word to convert .mht file to PDF ###
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
' ### Open .mht file we just saved and export as PDF ###
Set wrdDoc = wrdApp.Documents.Open(FileName:=bPath & saveName, Visible:=True)
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
pdfSave, ExportFormat:= _
wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=0, To:=0, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
wrdDoc.Close
wrdApp.Quit
' ### Delete .mht file ###
Kill bPath & saveName
Set oMail = Nothing
Set olNS = Nothing
Set fso = Nothing
End Sub
This will save a PDF file with the name like "Marty Smith 04-06-2020" however if I add the String "bDay" into the file name, it'll disregard the name, and the DOB, and only add the date, but Word will fail to save and hang in a background process.
' ### Save .mht file to create pdf from Word ###
oMail.SaveAs bPath & saveName, olMHTML
pdfSave = bPath & clientName & " " & bDay & " " & Format(oMail.ReceivedTime, "dd-mm-yyyy") & ".pdf"
If fso.FileExists(pdfSave) Then
plooper = 0
Do While fso.FileExists(pdfSave)
plooper = plooper + 1
pdfSave = bPath & clientName & " " & bDay & " " & Format(oMail.ReceivedTime, "dd-mm-yyyy") & " " & plooper & ".pdf"
Loop
Else
End If
My closing position for InStr included 2 newlines from the Email body, that wasn't apparent to me when I was showing the output via Msgbox.
Debug.Print bDay helped me to see what the issue was and adjusting the closePos variable to remove the newlines.
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
I have an Outlook macro that saves an email as a PDF. It is passed the name of the file (EmailName) from the subject\input box and the folder (strFolder) to save to.
I am using PDFTK to create the PDF.
I show the SaveAs dialog box to save.
If dlgSaveAs.Show = -1 Then
strCurrentFile = dlgSaveAs.SelectedItems(1)
Is there a way of saving the email as PDF without showing the SaveAs dialog box to confirm the file name\folder?
----------------------------------------------------------------------------
Public Function EVAL_SaveAsPDFfile(EmailName As String, strFolder As String) As String
'====================================================
' Description: Outlook macro to save a selected item in the pdf-format
' Requires Word 2007 SP2 or Word 2010
' Requires a reference to "Microsoft Word Object Library"
' (version is 12.0 or 14.0)
' In VBA Editor; Tools-> References...
'====================================================
' also microsoft shell controls and automation
'=============================================
' set share location
'=============================================
' On Error GoTo ErrorHandling
'Root folder
Dim strTempFileName As String
strTempFileName = "\\asfs1\cons\clients"
If (Right(strFolder, 1) = "\") Then
Else
strFolder = strFolder + "\"
End If
'PDFTK
Dim program As String
program = strTempFileName & "\crm\pdftk.exe"
Dim directoremail As String
directoremail = "email#address.co.uk"
FUNC_SYSTEM_FolderExistsCreate (strFolder)
FUNC_SYSTEM_FolderExistsCreate (strTempFileName)
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(strTempFileName) Then
'Get all selected items
Dim MyOlNamespace As Outlook.NameSpace
Set MyOlNamespace = Application.GetNamespace("MAPI")
Set MyOlSelection = Application.ActiveExplorer.Selection
'Make sure at least one item is selected
If MyOlSelection.Count <> 1 Then
Response = MsgBox("Please select a single item", vbExclamation, "Save as PDF")
Exit Function
End If
'Retrieve the selected item
Set MySelectedItem = MyOlSelection.Item(1)
'Get the user's TempFolder to store the item in
Dim tmpString As String
Dim tmpFileName As String, newFileName As String
tmpString = strTempFileName & "\crm\temp\" & Format(Now, "yyyyMMddHHmmss")
'construct the filename for the temp mht-file
tmpFileName = tmpString & ".mht"
'newFileName = tmpString & ".pdf"
newFileName = EmailName & ".pdf"
'Save the mht-file
MySelectedItem.SaveAs tmpFileName, olMHTML
'Create a Word object
Dim wrdApp As Word.Application
Dim wrdDoc As Word.document
Set wrdApp = CreateObject("Word.Application")
'Open the mht-file in Word without Word visible
Set wrdDoc = wrdApp.Documents.Open(FileName:=tmpFileName, Visible:=False)
'Define the SafeAs dialog
Dim dlgSaveAs As FileDialog
Set dlgSaveAs = wrdApp.FileDialog(msoFileDialogSaveAs)
'Determine the FilterIndex for saving as a pdf-file
'Get all the filters
Dim fdfs As FileDialogFilters
Dim fdf As FileDialogFilter
Set fdfs = dlgSaveAs.Filters
'Loop through the Filters and exit when "pdf" is found
Dim i As Integer
i = 0
For Each fdf In fdfs
i = i + 1
If InStr(1, fdf.Extensions, "pdf", vbTextCompare) > 0 Then
Exit For
End If
Next fdf
'Set the FilterIndex to pdf-files
dlgSaveAs.FilterIndex = i
'Get location of My Documents folder
Dim WshShell As Object
Dim SpecialPath As String
Set WshShell = CreateObject("WScript.Shell")
SpecialPath = WshShell.SpecialFolders(16)
'Construct a safe file name from the message subject
Dim msgFileName As String
msgFileName = MySelectedItem.subject
Set oRegEx = CreateObject("vbscript.regexp")
oRegEx.Global = True
oRegEx.Pattern = "[\\/:*?""<>|]"
msgFileName = Trim(oRegEx.Replace(msgFileName, ""))
'Set the initial location and file name for SaveAs dialog
'=============================================
' set default location
'=============================================
Dim strCurrentFile As String
If (TypeOf MyOlSelection.Item(1) Is Outlook.mailitem) Then
strCurrentFile = GetClientFolder(MyOlSelection.Item(1))
End If
If strCurrentFile = vbNullString Then
dlgSaveAs.InitialFileName = strFolder
Else
If FileFolderExists(strCurrentFile & "\") Then
dlgSaveAs.InitialFileName = strCurrentFile & "\"
Else
dlgSaveAs.InitialFileName = strFolder
End If
End If
dlgSaveAs.Execute
Set objFSO = CreateObject("Scripting.FileSystemObject")
' minimize outlook to show save as dialog
Set OutlookObj = GetObject(, "Outlook.Application")
OutlookObj.ActiveExplorer.WindowState = olMinimized
Dim objShell As Shell
Set objShell = New Shell
'' objShell.MinimizeAll
'Show the SaveAs dialog and save the message as pdf
newFileName = Replace(newFileName, ":", " -", Start:=1)
dlgSaveAs.InitialFileName = strFolder + newFileName
dlgSaveAs.Execute
If dlgSaveAs.Show = -1 Then
strCurrentFile = dlgSaveAs.SelectedItems(1)
'Verify if pdf is selected
If Right(strCurrentFile, 4) <> ".pdf" Then
Response = MsgBox("Sorry, only saving in the pdf-format is supported." & vbNewLine & vbNewLine & "Save as PDF instead?", vbInformation + vbOKCancel)
If Response = vbCancel Then
' wrdDoc.Close
' wrdApp.Quit
Exit Function
ElseIf Response = vbOK Then
intPos = InStrRev(strCurrentFile, ".")
If intPos > 0 Then
strCurrentFile = Left(strCurrentFile, intPos - 1)
End If
strCurrentFile = strCurrentFile & ".pdf"
End If
End If
'Save as pdf
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:=newFileName, ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=0, To:=0, Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, BitmapMissingFonts:=True, UseISO19005_1:=False
EVAL_SaveAsPDFfile = strCurrentFile
' now append the temp file with the chosen one
'=============================================
' set pdftk location
'=============================================
Dim tempPDF
tempPDF = tmpString & " temp.pdf"
' if existing file, append to old
If objFSO.FileExists(strCurrentFile) Then
Dim command As String
command = Chr(34) & program & Chr(34) & " " & Chr(34) & newFileName & Chr(34) & " " & Chr(34) & strCurrentFile & Chr(34) & " cat output " & Chr(34) & tempPDF & Chr(34)
Dim oShell
Set oShell = CreateObject("WScript.Shell")
fdsk = oShell.Run(command, 1, True)
Set oShell = Nothing
' MsgBox ("Temp: " & tempPDF + ", Current: " & strCurrentFile)
objFSO.CopyFile tempPDF, strCurrentFile, True
Else
' create file to be overwriten
Dim fsonewpdf As Object
Set fsonewpdf = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fsonewpdf.CreateTextFile(strCurrentFile)
oFile.WriteLine "test"
oFile.Close
Set fsonewpdf = Nothing
Set oFile = Nothing
objFSO.CopyFile newFileName, strCurrentFile, True
End If
'copy new file to saveas file
'delete temp files
If objFSO.FileExists(tempPDF) Then
objFSO.DeleteFile tempPDF
End If
If objFSO.FileExists(newFileName) Then
objFSO.DeleteFile newFileName
End If
'close the document and Word
wrdDoc.Close
'wrdApp.Quit
If objFSO.FileExists(tmpFileName) Then
objFSO.DeleteFile tmpFileName
End If
Else
' close the document and Word
wrdDoc.Close
'wrdApp.Quit
End If
If objFSO.FileExists(tmpFileName) Then
objFSO.DeleteFile tmpFileName
End If
' maximize outlook now that we have finished
''OutlookObj.ActiveExplorer.WindowState = olMaximized
'objShell.UndoMinimizeALL
Set objShell = Nothing
Set dlgSaveAs = Nothing
'Cleanup
Set MyOlNamespace = Nothing
Set MyOlSelection = Nothing
Set MySelectedItem = Nothing
Set wrdDoc = Nothing
Set wrdApp = Nothing
Set oRegEx = Nothing
End If
'ErrorHandling:
' MsgBox "The Email failed to save, please delete the Evaluation record and try again or manually save the email as a PDF and add it.", vbOKOnly, "Error Saving Email"
' EVAL_SaveAsPDFfile = ""
End Function
I have a folder full of Word Documents which has recently been "undeleted", while the contents of these files are viewable all metadata has been lost (Most importantly, original file names). I have found a VBA script that will run through a folder and rename any .doc files with the first line of its content.
The scripts works just as expected with documents that contain only text, although many of the files I need renamed are headed with an image. When the script gets to these files it ends and only the files up to that point are renamed.
I have very limited programming knownledge and know next to nothing about VBA but I imagine that I could skip the image with an if|else type statement and use the next line of text as the file name. My problem is I have no idea on how to accomplish this. Also, a method of removing any spaces which appear before the first line of text would be very helpful but is much less important.
The script I am currently working with is as follows:
Public Sub BatchReNameFiles()
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim NewName As String
Dim OldName As String
Dim oRng As Range
Dim i As Integer
Dim j As Integer
'Specify folder where files are located
PathToUse = "C:\Test\"
'Count files in folder
OldName = Dir$(PathToUse & "*.doc")
While OldName <> ""
i = i + 1
OldName = Dir$()
Wend
'Rename files
j = 0
myFile = Dir$(PathToUse & "*.doc")
Do While myFile <> "" And j < i
j = j + 1
Set myDoc = Documents.Open(FileName:=PathToUse & myFile, Visible:=False)
With myDoc
OldName = .FullName
Set oRng = .Words(1)
oRng.End = .Words(min(9, .Words.Count - 1)).End
NewName = Trim(oRng.Text) & ".doc"
NewName = Replace(NewName, "\", "")
NewName = Replace(NewName, ":", "")
NewName = Replace(NewName, """", "")
NewName = Replace(NewName, vbCr, "")
NewName = Replace(NewName, vbTab, "")
.Close SaveChanges:=wdSaveChanges
End With
Name OldName As PathToUse & NewName
myFile = Dir$()
Loop
End Sub
Private Function min(a As Long, b As Long)
min = -((a < b) * a + (a >= b) * b)
End Function
I take no credit for this script, I found it as is while browsing the web looking for a solution. If anyone has any insight into this problem I would greatly appreciate a response.
"My problem is I have no idea on how to accomplish this." I don't think this is how SO was designed to operate, but I think I can use this routine also. So here's my version, which I think is better. The 'net is short on VBA tutorials, but this looks good: http://word.mvps.org/FAQs/MacrosVBA/VBABasicsIn15Mins.htm.
Option Explicit
Public Sub BatchReNameFiles()
Const sPath = "c:\test\" ' could do FileDialog
Dim OldName$, NewName$, openDoc As Document
ThisDocument.Content.Delete
OldName = Dir$(sPath & "*.doc", vbNormal)
Do While OldName <> ""
ThisDocument.Activate
Selection.TypeText OldName & " -> "
Set openDoc = Documents.Open(sPath & OldName)
openDoc.Activate
NewName = getChars(20) & ".doc"
openDoc.Close
ThisDocument.Activate
If NewName <> ".doc" Then
Selection.TypeText NewName
On Error GoTo zError
Name sPath & OldName As NewName
On Error GoTo 0 ' reset
End If
Selection.TypeText vbCrLf
DoEvents
OldName = Dir$()
Loop
Exit Sub
zError:
Selection.TypeText "Error: " & Err.Description
Resume Next
End Sub
Function getChars$(nChars&) ' get good characters
Dim s1$, sChar$
Selection.HomeKey wdStory
Do
sChar = Chr$(Asc(Selection.Text)) ' one character
If "0" <= sChar And sChar <= "9" Or _
"A" <= sChar And sChar <= "Z" Or _
"a" <= sChar And sChar <= "z" Then
s1 = s1 & sChar
If Len(s1) = nChars Then Exit Do
End If
Loop While Selection.MoveRight(1, wdCharacter) <> 0
getChars = s1
End Function
EDIT: Try this minimum and add/uncomment statements to it. I'm baffled.
Option Explicit
Public Sub BatchReNameFiles()
' Const sPath = "c:\test\" ' could do FileDialog
' Dim OldName$, NewName$, openDoc As Document
' ThisDocument.Content.Delete
' OldName = Dir$(sPath & "*.doc", vbNormal)
' ThisDocument.Activate
Selection.TypeText "This is data"
' Selection.TypeText OldName & " -> "
End Sub
<pre>
Este funciona correctamente (is OK)
</pre>
-------------------------
Option Explicit
Sub FirstPara()
Application.ScreenUpdating = False
Dim strFolder As String, salFolder As String, docu As String, NombreCarpeta As String, strFile As String, wdDoc As Document
Dim FirstPara As String
Dim counter As Integer, a As Integer, i As Integer
strFolder = GetFolder
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "\*.doc*", vbNormal)
i = 0
a = 0
Do While strFile <> ""
i = i + 1
strFile = Dir
Loop
'MsgBox "value is " & i
While a < i
strFile = Dir(strFolder & "\*.doc*", vbNormal)
docu = strFolder & "\" & strFile
Set wdDoc = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
FirstPara = .Paragraphs(1).Range.Text
FirstPara = Left(FirstPara, Len(FirstPara) - 1)
NewName = Replace(FirstPara, "\", "")
NewName = Replace(NewName, "/", "")
NewName = Replace(NewName, ":", "")
NewName = Replace(NewName, """", "")
NewName = Replace(NewName, vbCr, "")
FirstPara = Replace(NewName, vbTab, "")
'MsgBox "value is " & FirstPara
NombreCarpeta = "\PROCESADOS"
'Comprueba que la carpeta no existe para crearla.
If Dir(strFolder & NombreCarpeta, vbDirectory) = "" Then MkDir strFolder & NombreCarpeta
'MkDir se emplea para crear un directorio/carpeta.
.SaveAs FileName:=strFolder & "\PROCESADOS\" & FirstPara & ".docx"
.Close
'Muevo el fichero a ORIGINALES.
NombreCarpeta = "\ORIGINALES"
'Comprueba que la carpeta no existe para crearla.
If Dir(strFolder & NombreCarpeta, vbDirectory) = "" Then MkDir strFolder & NombreCarpeta
'MkDir se emplea para crear un directorio/carpeta.
FileCopy docu, strFolder & "\ORIGINALES\" & strFile
Kill docu
a = a + 1
End With
Set wdDoc = Nothing
strFile = Dir()
Wend
Application.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function
-----------------------
Option Explicit
Sub FirstPara()
Application.ScreenUpdating = False
Dim strFolder As String, salFolder As String, docu As String, NombreCarpeta As String, strFile As String, wdDoc As Document
Dim FirstPara As String
Dim counter As Integer, a As Integer, i As Integer
strFolder = GetFolder
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "\*.doc*", vbNormal)
i = 0
a = 0
Do While strFile <> ""
i = i + 1
strFile = Dir
Loop
'MsgBox "value is " & i
While a < i
strFile = Dir(strFolder & "\*.doc*", vbNormal)
docu = strFolder & "\" & strFile
Set wdDoc = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
FirstPara = .Paragraphs(1).Range.Text
FirstPara = Left(FirstPara, Len(FirstPara) - 1)
NewName = Replace(FirstPara, "\", "")
NewName = Replace(NewName, "/", "")
NewName = Replace(NewName, ":", "")
NewName = Replace(NewName, """", "")
NewName = Replace(NewName, vbCr, "")
FirstPara = Replace(NewName, vbTab, "")
'MsgBox "value is " & FirstPara
NombreCarpeta = "\PROCESADOS"
'Comprueba que la carpeta no existe para crearla.
If Dir(strFolder & NombreCarpeta, vbDirectory) = "" Then MkDir strFolder & NombreCarpeta
'MkDir se emplea para crear un directorio/carpeta.
.SaveAs FileName:=strFolder & "\PROCESADOS\" & FirstPara & ".docx"
.Close
'Muevo el fichero a ORIGINALES.
NombreCarpeta = "\ORIGINALES"
'Comprueba que la carpeta no existe para crearla.
If Dir(strFolder & NombreCarpeta, vbDirectory) = "" Then MkDir strFolder & NombreCarpeta
'MkDir se emplea para crear un directorio/carpeta.
FileCopy docu, strFolder & "\ORIGINALES\" & strFile
Kill docu
a = a + 1
End With
Set wdDoc = Nothing
strFile = Dir()
Wend
Application.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function