There are two ways to save Outlook messages in PDF format: by printing to a PDF printer or saving in PDF format from Word. This sample shows how to use the Word Object Model to save as PDF. (There is a third way: use Adobe Acrobat's package feature. It makes a really nice PDF archive, if you own Acrobat.)
This code sample will save one or more selected Outlook email messages as a PDF file. Because it uses Word object to save, this code could easily be tweaked to save messages in any format Word can save as.
Don't forget to set a reference to the Word object library in Tools > References. Select the correct version for your version of Office. (Most people will only have one entry, the correct one.)

A version of this macro to use in a run a script rule is here.
Sub SaveMessageAsPDF()
Dim Selection As Selection
Dim obj As Object
Dim Item As MailItem
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
Set Selection = Application.ActiveExplorer.Selection
For Each obj In Selection
Set Item = obj
Dim FSO As Object, TmpFolder As Object
Dim sName As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set tmpFileName = FSO.GetSpecialFolder(2)
sName = Item.Subject
ReplaceCharsForFileName sName, "-"
tmpFileName = tmpFileName & "\" & sName & ".mht"
Item.SaveAs tmpFileName, olMHTML
Set wrdDoc = wrdApp.Documents.Open(FileName:=tmpFileName, Visible:=True)
Dim WshShell As Object
Dim SpecialPath As String
Dim strToSaveAs As String
Set WshShell = CreateObject("WScript.Shell")
MyDocs = WshShell.SpecialFolders(16)
strToSaveAs = MyDocs & "\" & sName & ".pdf"
' check for duplicate filenames
' if matched, add the current time to the file name
If FSO.FileExists(strToSaveAs) Then
sName = sName & Format(Now, "hhmmss")
strToSaveAs = MyDocs & "\" & sName & ".pdf"
End If
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
strToSaveAs, 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
Next obj
wrdDoc.Close
wrdApp.Quit
Set wrdDoc = Nothing
Set wrdApp = Nothing
Set WshShell = Nothing
Set obj = Nothing
Set Selection = Nothing
Set Item = Nothing
End Sub
' This function removes invalid and other characters from file names
Private Sub ReplaceCharsForFileName(sName As String, sChr As String)
sName = Replace(sName, "/", sChr)
sName = Replace(sName, "\", sChr)
sName = Replace(sName, ":", sChr)
sName = Replace(sName, "?", sChr)
sName = Replace(sName, Chr(34), sChr)
sName = Replace(sName, "<", sChr)
sName = Replace(sName, ">", sChr)
sName = Replace(sName, "|", sChr)
sName = Replace(sName, "&", sChr)
sName = Replace(sName, "%", sChr)
sName = Replace(sName, "*", sChr)
sName = Replace(sName, " ", sChr)
sName = Replace(sName, "{", sChr)
sName = Replace(sName, "[", sChr)
sName = Replace(sName, "]", sChr)
sName = Replace(sName, "}", sChr)
sName = Replace(sName, "!", sChr)
End Sub
Save without the Headers
This version of the macro saves the message without the short To/From/subject headers normally found at the top of a printed message.

Sub SaveMessageAsPDF()
'Set up the browser
Dim browser As String
Dim ConvertMail As Boolean
Dim CheckHTML As Boolean
browser = "C:\Program Files\Internet Explorer\iexplore.exe"
ConvertMail = False
CheckHTML = True
Dim Selection As Selection
Dim obj As Object
Dim Item As MailItem
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
Set Selection = Application.ActiveExplorer.Selection
For Each obj In Selection
Set Item = obj
Dim FSO As Object, TmpFolder As Object
Dim sName As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set tmpFileName = FSO.GetSpecialFolder(2)
sName = Item.Subject
ReplaceCharsForFileName sName, "-"
tmpFileName = tmpFileName & "\" & sName & ".htm"
Dim ConvertHTML As Boolean
ConvertHTML = True
If Item.BodyFormat = olFormatHTML And ConvertMail = False Then
Dim rawHTML As String
rawHTML = Item.HTMLBody
If CheckHTML = False Then
ConvertHTML = False
Else
If InStr(UCase(rawHTML), UCase("src=""cid:")) = 0 Then
ConvertHTML = False
End If
End If
End If
If ConvertHTML = False Then
Set objFile = FSO.CreateTextFile(tmpFileName, True)
objFile.Write "" & rawHTML
objFile.Close
Set objFile = Nothing
Else
Item.SaveAs tmpFileName, olHTML
End If
Set wrdDoc = wrdApp.Documents.Open(FileName:=tmpFileName, Visible:=True)
Dim WshShell As Object
Dim SpecialPath As String
Dim strToSaveAs As String
Set WshShell = CreateObject("WScript.Shell")
MyDocs = WshShell.SpecialFolders(16)
strToSaveAs = MyDocs & "\" & sName & ".pdf"
' check for duplicate filenames
' if matched, add the current time to the file name
If FSO.FileExists(strToSaveAs) Then
sName = sName & Format(Now, "hhmmss")
strToSaveAs = MyDocs & "\" & sName & ".pdf"
End If
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
strToSaveAs, 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
Next obj
wrdDoc.Close
wrdApp.Quit
Set wrdDoc = Nothing
Set wrdApp = Nothing
Set WshShell = Nothing
Set obj = Nothing
Set Selection = Nothing
Set Item = Nothing
End Sub
' This function removes invalid and other characters from file names
Private Sub ReplaceCharsForFileName(sName As String, sChr As String)
sName = Replace(sName, "/", sChr)
sName = Replace(sName, "\", sChr)
sName = Replace(sName, ":", sChr)
sName = Replace(sName, "?", sChr)
sName = Replace(sName, Chr(34), sChr)
sName = Replace(sName, "<", sChr)
sName = Replace(sName, ">", sChr)
sName = Replace(sName, "|", sChr)
sName = Replace(sName, "&", sChr)
sName = Replace(sName, "%", sChr)
sName = Replace(sName, "*", sChr)
sName = Replace(sName, " ", sChr)
sName = Replace(sName, "{", sChr)
sName = Replace(sName, "[", sChr)
sName = Replace(sName, "]", sChr)
sName = Replace(sName, "}", sChr)
sName = Replace(sName, "!", sChr)
End Sub
Save as a DOCX File
To save the message as a Word Document using the DOCX file type, replace the code blocks that saves as a pdf with the code below.
wrdApp.ActiveDocument.SaveAs2 FileName:= _
strToSaveAs, FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
:=False, SaveAsAOCELetter:=False, CompatibilityMode:=15
How to Use Macros
First: You will need macro security set to low during testing.
To check your macro security in Outlook 2010 and above, go to File, Options, Trust Center and open Trust Center Settings, and change the Macro Settings. In Outlook 2007 and older, it’s at Tools, Macro Security.
After you test the macro and see that it works, you can either leave macro security set to low or sign the macro.
Open the VBA Editor by pressing Alt+F11 on your keyboard.
To put the code in a module:
- Right click on Project1 and choose Insert > Module
- Copy and paste the macro into the new module.
More information as well as screenshots are at How to use the VBA Editor
More Information
- How to Save Email in Windows File System
- Import Messages from File System into Outlook Folders
- OWA: Save Messages to My Documents
- Save a Message as HTML and Delete the (Annoying) Folder
- Save email message as text file
- Save Outlook Email as a PDF
- Save Selected Email Message as .msg File
- Saving All Messages to the Hard Drive Using VBA
Print Email (and Attachments) on Arrival has a list of utilities that can print messages and attachments.
Pedro says
Hi Diane,
is it possible to prompt for the file location on a save as dialog?
Thanks
Diane Poremsky says
You can use the browse for folder option in this article - https://www.slipstick.com/developer/code-samples/windows-filepaths-macro/
Pedro says
Hi Diane,
i don't know what to change in the code to include BrowseForFolderCan you help?
Thanks
Pedro says
Hi Diane,
i don't know what part of the code to modify.
Can you help please?
Kennan Bieniawski says
I have code similar to this shown below. However I am having trouble as when saving emails that have photos they are often cut-off. I can't seem to find a way to get the photos to either shrink to fit the dimensions or some other method.
James Martin says
Hi Kennan,
See the txt file of my bas file for my Macro Es. I use upper or lowercase initials for my Macros. Macro E is to save the email Header and body to Word.
Towards the end of the macro you will see Macro s , to force high res embedded images to within the page margin.
I have not cleaned out noted out code, as I have not resolved if Macro Es is run with Word App not open - I have to end task for the Word entry lower down in Task Manager, if run with Word App closed.
The way I have saved the email details for the file name should be of interest. A lot of trial and error.
There is some recent code added to flash up a MsgBox, for Macro L, in Excel which logs all my active windows, and productivity data, this is posted on my LinkedIn page.
James Martin says
In addition to my previous comment, I also have amended versions of the Slipstick save attachments to a folder "save-attachments-to-the-hard-drive". Macro A.
And the Slipstick macro for saving a txt version of an email, if needed. I call this Macro e "save-email-message-text-file".
These 3 macros including Macro Es were critical to I'mproving productivity.
There is a 4th Macro in Word to import image files downloaded from the Macro A to a temp folder you specify, and Import them at the cursor point. This saves a lot of time for an archiving role I have been doing.
For pdfs I have not created a macro to control the pages if under 11 pages (we have a 4MB file upload limit), and import these at the cursor point. I am manually rotating pdfs to landscape, full screening, and pasting into the docx.
I have Macro R to rotate all or selected images. (via Grey Maxey).
I also have Macro C/c to compress images by 150/96ppi.
Macro B for page/section Break, and Header and Footer unlink - is from Greg Maxey.
Macro S is to maximise images, as they shrink when moved in the document.
Macro T is to force tables mainly in email signatures to the page width, but does not always work on the cybertext.wordpress.com website "word-macro-to-autofit-all-tables-to-the-window-size/".
Macro P is to Print, open doc/docx/rtf/odt to pdf in the Temp attachments folder, so I can insert easily into the Macro Es docx save.
Macro X closes the active file in Word, although a minor action this saves a lot of time each day, as I use it so often.
All my macros are single click on the Quick Access Toolbar.
James Martin says
I have got the pdf Outlook Item Macro to work, with change to docx with Header, as this file type is better for editing the order of embedded customer photos of documents. I need some code when the objects/items from outlook are moved to Word, before the saving.
Basically customers upload images of document pages from mobiles, and the images are embedded in the email body and not classed as attachments. Most photos are oversized in the docx produced.
I currently forward selected email and copy the Forwarded email body and paste H into docx and this naturally wraps all images within the margins even if in landscape.
[I have a rotation macro to correct selected or all images by 90, 180 or 270 degrees, I received help from http://www.gregmaxey.com to get the two listboxes to work in a UserForm for the select or all rotation macros.]
I have noticed cutting the images in the docx from the run macro and repasting with paste K, resolves the wrapping problem, but I am struggling to code this. The other problem with my manual method is that the attachments list is not included in the forwarded email body and the most recent email header, so if I code this it would not be ideal (too complicated for me to code).
Any help for a probable simple coding solution, would be greatly received. I need this Macro, along with the save email as text, and save all attachments which I have got to work from this site
[for the attachments macro I added:
Kill "C:\folder\folder2\*.*"
To clear the folder up a level from where the docx and txt macros are saved, before each run of the attachments macro, the kill code is the first line of the sub.
Philip Coltharp says
Thank you Diane, thank you, thank you, thank you, thank you, thank you ...
Matt Lane says
Hey Diane, Thank you for posting. Love how the code includes the headers. Having a bit of trouble. When i select items from my inbox, it saves them to the specified desktop folder. When i try to select emails from a sub folder of my outlook inbox, I run into an error "Outlook cannot save this file because it is already open elsewhere." on the following line of code: Item.SaveAs tmpFileName, olMHTML. I like saving the emails to a subfolder as i need to save them for an access review. I have an outlook rule moving ~1000 of them to the subfolder so i can group them. Any ideas? Thanks!
Tapas says
Hi Diane,
I have an email that has a table (or a picture) in it that gets cropped when i use this macro to save as pdf. Any suggestions to fit all data to a page in the pdf?
Javier says
Hello Diane. When I have selected a confirmation (example: Accepted: invitation ...) this won't work and throw an error in here:
For Each obj In SelectionSet Item = obj
The error message is:
Run-time error '13': Type missmatch
I guess confirmations are a different object.
Do you know how I can fix it? I want to gather information from aa bunch of meeting confirmations.
Thanks in advance.
Neelesh says
I get a debug error at
Set objFile = FSO.CreateTextFile(tmpFileName, True)Sub SaveMessageAsPDF()'Set up the browser
Dim browser As String
Dim ConvertMail As Boolean
Dim CheckHTML As Boolean
browser = "C:\Program Files\Internet Explorer\iexplore.exe"
ConvertMail = False
CheckHTML = True
Dim Selection As Selection
Dim obj As Object
Dim Item As MailItem
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
Set Selection = Application.ActiveExplorer.Selection
For Each obj In Selection
Set Item = obj
Dim FSO As Object, TmpFolder As Object
Dim sName As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set tmpFileName = FSO.GetSpecialFolder(2)
sName = Item.Subject
ReplaceCharsForFileName sName, "-"
tmpFileName = tmpFileName & Format(Now, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem) & sName & ".htm"
Dim ConvertHTML As Boolean
ConvertHTML = True
If Item.BodyFormat = olFormatHTML And ConvertMail = False Then
Dim rawHTML As String
rawHTML = Item.HTMLBody
If CheckHTML = False Then
ConvertHTML = False
Else
If InStr(UCase(rawHTML), UCase("src=""cid:")) = 0 Then
ConvertHTML = False
End If
End If
End If
If ConvertHTML = False Then
Set objFile = FSO.CreateTextFile(tmpFileName, True)
objFile.Write "" & rawHTML
objFile.Close
Set objFile = Nothing
Else
Item.SaveAs tmpFileName, olHTML
End If
Set wrdDoc = wrdApp.Documents.Open(FILENAME:=tmpFileName, Visible:=True)
Dim WshShell As Object
Dim SpecialPath As String
Dim strToSaveAs As String
Set WshShell = CreateObject("WScript.Shell")
MyDocs = WshShell.SpecialFolders(16)
strToSaveAs = MyDocs & Format(Now, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem) & sName & ".pdf"
' check for duplicate filenames
' if matched, add the current time to the file name
If FSO.FileExists(strToSaveAs) Then
sName = sName & Format(Now, "hhmmss")
strToSaveAs = MyDocs & "\" & sName & ".pdf"
End If
wrdApp.ActiveDocument.ExportAsFixedFormat OutputFileName:= _
Diane Poremsky says
Does it give you an error message or just stop at that line? What do you have set for the filepath?
tmpFileName = tmpFileName & Format(Now, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem) & sName & ".htm"
PaulD says
I just tried this with Outlook 2007 and Word 2003. Stepping through the code it generates the temp file, but fails to generate the pdf file. VBA isn't generating any errors and the macro happily runs to the end. Any idea what is going on?
Diane Poremsky says
Does it skip any lines? Is the Word version a typo? Word 2003 may not support saving as PDF.
Comment out all error handlers so it stops on errors. You may need set the editor to break on all errors - it usually only breaks on unhandled errors.
PaulD says
Thanks for the tip. Yes Word 2003 cannot save to pdf. Never thought to check that. So I printed to a pdf printer addin which achieves the same result. Cheers
IzaB says
Windows 10 was blocking it, so I used a workaround you have for it and it is working now :)
IzaB says
Hello Diane,
I have the same problem. it generates the temp file, but fails to generate the pdf file. VBA isn't generating any errors and the macro happily runs to the end. I've word 2016 & outlook 2016. Any suggestions what I should do?
Esteban Ramos says
Hello again Diane,
Is there a way to have the message saved as DOCX directly to a specified folder without any prompts?
Thanks,
Esteban R.
Diane Poremsky says
You can use a macro - an automatic startup macro will save all as they arrive or you can use a manual one - select the message, push a button. Either can be preconfigured to use either a hardcoded path.
Esteban Ramos says
Thank you, using the code what changes can I make to save it so a path?
I see:
strToSaveAs = MyDocs & "\" & sName & ".docx"
' check for duplicate filenames
' if matched, add the current time to the file name
If FSO.FileExists(strToSaveAs) Then
sName = sName & Format(Now, "hhmmss")
strToSaveAs = MyDocs & "\" & sName & ".docx"
End If
Not sure what to edit to change to a specified path
Diane Poremsky says
If you want to save to a specific path, you can change this line:
strToSaveAs = MyDocs & "\" & sName & ".docx"
to
strToSaveAs = "c:\The new path\folder\subfolder\" & sName & ".docx"
Esteban Ramos says
Diane thanks for the replies, I changed the code as seen below. However it still save to Documents and not the specified folder. Im guessing it has to do with the 'Mydocs = wshell.special folders' line.
--------------------------------------------------------------------------------------------
Set wrdDoc = wrdApp.Documents.Open(FileName:=tmpFileName, Visible:=True)
Dim WshShell As Object
Dim SpecialPath As String
Dim strToSaveAs As String
Set WshShell = CreateObject("WScript.Shell")
MyDocs = WshShell.SpecialFolders(16)
strToSaveAs = "C:\Users\gonzae50\Documents\NEWVITALIZEEMAILS" & sName & ".docx"
' check for duplicate filenames
' if matched, add the current time to the file name
If FSO.FileExists(strToSaveAs) Then
sName = sName & Format(Now, "hhmmss")
strToSaveAs = "C:\Users\gonzae50\Documents\NEWVITALIZEEMAILS" & sName & ".docx"
End If
wrdApp.ActiveDocument.SaveAs2 FileName:= _
strToSaveAs, FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
:=False, SaveAsAOCELetter:=False, CompatibilityMode:=15
---------------------------------------------------------------------------------------------
Do you know what I can do to get it to the folder?
Thank you SO MUCH for all the amazing help!
Esteban Ramos says
Just an FYI the path has all the "/" not sure why they didn't come across on the pasting of the code.
Diane Poremsky says
It's wordpress - or, more accurately php - it removes the slashes. :(
Diane Poremsky says
You aren't using mydocs. or shouldn't be. Comment out or delete that line and see if it errors. Do you have a slash after the folder name ? This: Documents\NEWVITALIZEEMAILS" & sName & ".docx" = Documents\NEWVITALIZEEMAILSsname.docx
Use a trailing slash in the strtosaveas path: Documents\NEWVITALIZEEMAILS\"
Heather G Licklider says
how can I change the file saving naming convention to the Sent on date in the format "yyyy-mm-dd-hh-nn-ss-subject"
Diane Poremsky says
Use Format(obj.SentOn, "yyyy-mm-dd-hh-nn-ss-") & obj.subject
Sam says
I often get an error with the .mht file still being open and not closing. This often happens if you run the script multiple times on the same email, but will also do it randomly.
More importantly, when I restart my computer, several word documents open. It's as if the email is converting but the file stays open in the background, maybe in a temp file?
Is there a way to "Kill" this? I have tried the kill command but it doesn't work.I think it has to do with this tmpFileName
One last thing, If you run the script on the same email multiple times, it doesn't create another version. It says errors. I thought adding the date format after the name, as it looks like you did, but I couldn't get yours to work, nor mine.
sName = sName & Format(dtDate, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem)Diane Poremsky says
>>
More importantly, when I restart my computer, several word documents open. It's as if the email is converting but the file stays open in the background, maybe in a temp file?
>>
Windows 10? There is an option to reopen apps that were open when you closed Windows. I'm guessing that is the reason they reopen. Change this in Settings > Accounts > Sign-in Options to finish setting up apps after logging in.
https://www.slipstick.com/outlook/outlook-loads-computer-boots/
>>
One last thing, If you run the script on the same email multiple times, it doesn't create another version. It says errors. I thought adding the date format after the name,
>>
That should be because the file already exists.
Does it work if you use Now for the date?
sName = sName & Format(Now, "yyyy-mm-dd", vbUseSystemDayOfWeek, vbUseSystem)Amanda says
I have been using this script and the rule version of it for months. But all of a sudden I came into work this morning, and it's freezing outlook until i pull up task manager and find the WINWORD.EXE *32 process and end it. It is creating these and not closing them? The date is June 4th 2018. I'm not sure why i'm getting this error now, when in the past it's been fine.
Jim Bo says
Hi Dianne - me again!
All working well, except when the script tries to run, i get the following error. If i restart my computer it works again?:
Run-time error '-2147467259 (80004005)': The export failed due to an unexpected error.
What should i do? I have attached shots of the error and the screen reached with the debugger
Diane Poremsky says
What version of Office, Windows do you use? I can't find much information about possible causes for that error - but what i found involved Office 2007. I'm still looking for solutions.
Jim Bo says
I am using Windows 10 Pro / Office 2013
Diane Poremsky says
Also, what pdf application do you use? This is the only comment I've found so far that the affected user said worked: "I uninstalled Foxit Reader and installed Adobe Reader 9 and rebooted..."
I don't think the error message points to the filename, but triple check t o verify it is valid.
Jim Bo says
I use Adobe Acrobat Reader DC. what do i need to check with the filename?
The odd thing is it works fine after a reboot but then finally stops so i need to reboot?
Diane Poremsky says
I'm not sure what you need to do - there is so little information out there, at least that I've found.
Jim Bo says
Hi Diane. Just found i have an error with Word - some fonts it does not like - says there is not sufficient memory space to display the requested font. How do I change the font in the script to run as a rule?
Diane Poremsky says
This script doesn't use fonts - the message and files would use the default fonts for word or the one used in the email.
Is it a Type 1 font? They aren't supported in office 2013/2016. https://www.poremsky.com/office/type-1-and-other-older-fonts-not-supported-in-office-2013/
Denny says
Hi Diane,
Is me again. I trying to do it again in a new company environment.
This time, when i try to choose the script in the Rules, i can't find the any record there.
Diane Poremsky says
You can't find the script? Are you using the one with Sub SaveMessageAsPDF(Item As Outlook.mailItem) as the title? (It's at
https://www.slipstick.com/files/run-a-script-rule-save-as-pdf.txt)
Bishwarup Dutta says
I get an error 'Method or data member not found' and
Application.ActiveExplorer.Selection is highlighted
Diane Poremsky says
Do you have one or more messages selected? That error basically says it can't find email in the selection. Also, it needs to be actual email messages, not read receipts, NDRs, meeting requests etc.
Joe says
Hi Diane
I have set the script version up to run automatically which is fine. But i have the first version on this page added as a macro and a button on the ribbon to run it. The button does nothing. Another button I've added using your macro to save attachments works fine. All these are signed by my own cert and macro security is set low as possible. What am i doing wrong? All i have changed is the location of the saving folder (which i also did successfully in the other two mentioned macros)
Diane Poremsky says
>> All i have changed is the location of the saving folder (which i also did successfully in the other two mentioned macros)
Oh... make sure the path is correct.
After this line, add another msgbox
Set tmpFileName = your path 'FSO.GetSpecialFolder(2)
msgbox tmpFileName
and one after this
tmpFileName = tmpFileName & "\" & sName & ".mht"
msgbox tmpFileName
Are the paths correct?
Joe says
Thanks Diane
I found another workaround - added in a click, and it has worked fine since SaveMessageAsPDF_Click()
Jim Bo says
Thanks Diane
Just one issue, i have got the automatic script one running fine. But i tried to ad the first one on this page as a macro then call it up with a button on the ribbon but it doesnt work? the button next to it - another of your macros - to save the attachments works fine, but when i click this it doesnt do anything. I have signed them all with my own cert and have macro setting on lowest available. Also when i run it from the editor it works a charm, just not from the button. Any clues?
Diane Poremsky says
it runs on a selection, so as long as a message is selected, it should work. Add msgbox "It's working" as the first line - i think you'll find the button is working but something else is not.
You can also add a msgbox after this line to pop up the message subject. That will show that its getting into the loop.
Set Item = obj
msgbox item.subject
Richard says
A really great macro Diane
Kelvin says
Dear Diane,
Thank you for sharing this VBA script. It is work and helpful. I have one issue that the PDF cannot show the full page, is there any way to solve it?
Thanks
Diane Poremsky says
is it not saving all of the pages or is the page scaled to the wrong size?
Kelvin says
it is saving all page,but the page size may be wrong. how to control it?
for example:
email content show:
abcdefghijklmnopqrstuvwxyz
123456789123456789123456
after convert to pdf:
abcdefghijklmnopqrst
123456789123456789
Diane Poremsky says
I don't believe you can control it in code, it uses the default settings for the application.
Bharat Devana says
Hello,
Thanks for the code. Its working like a charm. Is there a way that I can save the messages as .tif? Let me know.
Diane Poremsky says
if word can save as a tif, definitely, otherwise, it depends on the program you use to view tif's. it need to support vba control or command lines.
Bharat Devana says
I have MS Document Image writer as the tif printer. Is there a possibility to it and print the messages in Tif? Could you help with the code?
Diane Poremsky says
open word. if the Developer ribbon is not visible (2010 and up) enable it in file, options, customize ribbon. On the Developer tab, click the button to record a macro then save/print the document (probably a blank page - that's fine) as tif. stop the recorder and get the code for ExportAsFixedFormat - beginning at ExportFormat:=, replace it with the code to save as tif.
if it's not using exportasfixed format, you may need to do more editing to the save block to make it work.
Rob Anrtt says
Can this code be altered to save attachemnts as well?
Diane Poremsky says
yes, you can add code to save the attachment, either before or after printing. Code samples showing how to save are here https://www.slipstick.com/developer/save-attachments-to-the-hard-drive/ and here https://www.outlook-tips.net/code-samples/save-and-delete-attachments/
Jacqueline says
Dear Diane,
I tried using your code in Excel VBA but I kept getting the error message, "Compile error: Can't find project or library" although I did set the reference to the Word object library in Tools > References.
Any advice, please? Thanks.
Diane Poremsky says
This code runs as an outlook macro - to run it from excel you also need to properly reference and call outlook object model.
joe says
Hey Diane, I've been looking all over your site, but haven't found anything so i thought I'd just ask....do you have anything on how to access the acrobat add-in (if you have it) in order to save messages as pdf's? I am really hoping that I can access the add-in to do something like "oMail.SaveAs sPath & sName & ".pdf", olPDF" rather than using the Word work around?
I haven't been able to find anything on this anywhere...
Thanks,
Joe
Diane Poremsky says
I'm not sure how much is exposed in the addin, but you might be able to call acrobat vba to print to it.
Stefan says
Dear Diane,
you just saved me so much time and trouble writing such a skript myself.
Thank you!
Stefan
Michael Kulawig says
Dear Diane
thank you for this nice piece of code, in one of the previous post a user asked for the option to open the "save as" dialog, did you find af solution for this ?
greetings from Denmark
Michael
Diane Poremsky says
i don't have a code sample, but this page has some information - https://msdn.microsoft.com/en-us/library/aa219843(office.11).aspx
Martin V says
Hi everyone,
Thank you for the code, this is some really good work here,
I'm getting an error message though " Object required, with one of the first lines of code sName=Item.Subject,
I can't understand why,
any idea?
Thanks a lot
Diane Poremsky says
do you have one or more email messages selected?
Nate says
Getting an error:
Compile Error: User-defined type not defined.
Then highlights this line "Dim wrdApp As Word.Application"
Suggestions?
Diane Poremsky says
Did you set a reference to the Word object library in Tools > References?
Thierry says
Hello,
I have one error : "Compile Error: Undefined variable"
for : "tmpFileName "
I have "Micorsoft Word 16.0 Object Livrary" and " Microsoft Scripting Runtime" are selected.
Thanks,
Thierry
Diane Poremsky says
Add Dim tmpFileName as string at the top with the other Dim lines.
gerrit says
This is a great post, but we are in need of removing the header information (from, to, subject, date info) so that the it would render the same way as opening an email in the browser and printing from there. Is there any way to modify this code to only include the body of the email? that would be a HUGE help. thanks
Diane Poremsky says
Replace
Item.SaveAs tmpFileName, olMHTML
with these lines
Dim ConvertHTML As Boolean
ConvertHTML = True
If Item.BodyFormat = olFormatHTML And AlwaysConvert = False Then
Dim rawHTML As String
rawHTML = Item.HTMLBody
If CheckHTML = False Then
ConvertHTML = False
Else
If InStr(UCase(rawHTML), UCase("src=""cid:")) = 0 Then
ConvertHTML = False
End If
End If
End If
If ConvertHTML = False Then
Set objFile = FSO.CreateTextFile(tmpFileName, True)
objFile.Write "" & rawHTML
objFile.Close
Set objFile = Nothing
Else
Item.SaveAs tmpFileName, olHTML
End If
Add these lines at the top of the macro
Dim browser As String
Dim AlwaysConvert As Boolean
Dim CheckHTML As Boolean
browser = "C:\Program Files\Internet Explorer\iexplore.exe"
AlwaysConvert = False
CheckHTML = True
Jay says
Hi Diane
First, let me thank you for this post and in helping 'confused.com' people like me.
I work for academic bureau and we have the habit to save pdf file of all correspondences sent to sponsors abroad. However, I thought to ask you of the possibility in using your Macro in converting old e.mails/attachments to a specific desktop folder all at once.
Sorry if my query is irrelevant ..!
Diane Poremsky says
The first macro works with the selected messages - can be one or more messages.
Bill Shannon says
Brilliant.
We have a document imaging system that allows us to import TIFF and PDF documents. Currently our incoming faxes are stored in a network share and are imported routinely by our scanning department.
Using this script we'll be able to catch more communication by implementing it to the senior staff. With a few modifications they'll be able to store an entire email thread to the same network share and will be imported as part of our pre-existing routine.
I did add a few extra lines in so that I can grab the users login name and stuff it in the title of the resulting PDF. Helps the scanning department to determine where to put the documents.
Again, thanks so much for this code!
Don says
How can this code be modified to send only the header contents of the email:?
From:
To:
Date:
Subject:
wrdApp.ActiveDocument.ExportAsFixedFormat
Many thanks,
Don
Don says
Hi Diane,
I am glad I found your website. It is partly what I was looking for :-)
I have a requirement which seems difficult to me. I will explain it as below:
We have a system which picks up the .pdf file from the email and uploads it in a system. We would like to have a macro, where the email body is appended at the end of the invoice pdf attachment.
This macro checks if there is a .pdf attachment in the email.
If yes then
Copy the contents of the email body
Paste it at the end of the attached pdf file
Save the pdf attachment of the email
Save the email.
So that when our system uploads this pdf it contains the actual invoice details and also also the email body in the file.
Diane, is this possible and how can this be done?
Many thanks for your reply. Looking forward to hearing from you.
Best regards,
Don
Diane Poremsky says
This part > Paste it at the end of the attached pdf file is the hard part. You need to use a pdf editor that can be controlled by VBA. It might work in Word, provided it does not mess up the PDF formatting. (I have some PDFs that look awful in Word.) Adobe Acrobat supports VBA but I've only used it for simple things, like printing, and have no idea how to do it using Acrobat.
Ashley says
Would you/your users all have access to Acrobat?
I spent a couple weeks fiddling with this code and using it to do something similar. I save the e-mail as a PDF, then save all of the attachments, convert them to PDFs if they aren't already (using VBA+acrobat), then attach the attachments at the end of the e-mail PDF.
Depending on how your macro picks up the attachment and interacts with your system, my code could potentially work for you..
Would your system be able to detect/pick up a file that was saved and combined in the temp folder (or any other windows folder) and THEN upload it, rather than trying to do it all without leaving outlook?
Olivia says
Do you have a code for this? I need to download about 6,000 emails, all with multiple attachments and make each email with it's attachments into one pdf. I'm looking for a code that I can just run once on the folder containing all of the emails. I have access to acrobat for this
Diane Poremsky says
No, i don't currently have code that turns both the email and the attachment into a pdf. Adobe Acrobat has an addin that can do it - they have a free trial so you can see if it meets your needs. I'm not sure if any other pdf programs have a similar feature but its worth checking out.
Rajesh Chawda says
As written by you that Adobe Acrobat has an addin that can turn both the email and the attachment into a pdf -
my query is that if we have hundreds of such pdf emails (each having another pdf as an attachment to the email ( in other words a pdf embedded in another pdf ), then
Can a VBA macro code help in opening the embedded pdf document (from the pdf email) to extract some information ?
Would you have some readymade vba code to do so?
OR Can you guide some link where such a similar code is shared ?
I am required to do this for hundreds of emails every week, which eats away more than 6-7 valuable hours every week.
Diane Poremsky says
I don't have any code that will open it, but it may be possible as long as you use Acrobat.
Keep in mind that when you create a package, the attachment is just another page in the pdf, which could make it easier to access using code.
Michael says
Hi Diane,
Thanks for this. It works great and this is going to save me a lot of time in the future. Right now, the script saves the files to my Documents folder. Would it be possible for me to create a special file in Documents, and then have all of files saved to that discreet folder?
Thanks in advance.
Diane Poremsky says
Sorry I missed this before - sure you can change it. These lines set the path:
MyDocs = WshShell.SpecialFolders(16)
strToSaveAs = MyDocs & "\" & sName & ".pdf"
just add the folder name to it
strToSaveAs = MyDocs & "\newfolder\" & sName & ".pdf"
if it's not under my docs, use the full pATH:
strToSaveAs = "D:\my stuff\folder\" & sName & ".pdf"
GVB says
Hello, Thanks for the code. IO converts the email message, I would like to know how to convert to pdf along with the attachments.
Thanks in advance.
Diane Poremsky says
What file type are the attachments? Outlook needs to open the attachment then control the application to save as pdf or print to pdf. I have some code samples at print attachments as they arrive that show how to send attachments to the printer. It will create separate files though - if you want one file it would be more efficient to use an addin.
Diane Poremsky says
Print Email (and Attachments) on Arrival has a list of utilities that can print messages and attachments.
Matt O'Brien says
A temp file is stored in ........AppData\Local\Temp.
I am getting file exists errors .......
Should these temp files be cleared by some method.
(Ps... Thanks for a brilliant piece of code..... a really brilliant piece of code)
Diane Poremsky says
Type %temp% in the address bar of windows explorer and press enter to open the temp location then delete the files.
Michele says
Hi Diane,
I receive an "unable to save the file ... mht" "the file is already open"
How can I fix?
Thank you
Diane Poremsky says
Is it open in IE? I think that is the only program that can read mht files.
Mike says
Check file name length. I run into this issue when my subject line is extremely long. To fix it, I updated the following:
sName = Item.Subject
to
sName = Mid(Item.Subject, 1, 20) & "-" & Format(Item.SentOn, "yyyy-mm-dd")
Adjust the desired length from 20 to whatever you like.
Denny says
Hi Diane,
Thanks for your guidance, the rules and script work perfectly.
Just a little more request, can i make the file name more meaningful as in the file name able to capture certain keywords from the email content?
Diane Poremsky says
The filename is set here -
sName = Item.Subject
it can use any field in the email - if you want to grab words from the body, you'd need to use instr or regex.
If you have a specific set of unique words to look for, I'd probably use an array. Using the first sample at https://www.slipstick.com/developer/using-arrays-outlook-macros/, change the if line to
If InStr(LCase(Item.body), arrCat(i)) Then sname = arrCat(i)
When a keyword is matched, it uses it in the filename (can add it to the filename: sname = arrcat(i) & item.subject).
the big thing is the keywords need to be unique.
If you are looking for something that will be preceded by specific text and will vary with each message, like
Name: Bill Smith
you'll use regex to find the text and keyword.
Regex sample: https://www.slipstick.com/developer/regex-parse-message-text/
Tiffany says
Is there a way to add just the sent date without the time? I used the Item.SentOn and got everything when I really just want the received date.
Diane Poremsky says
use format( Item.SentOn, "yyyy-mm-dd")
you can use pretty much any date format you want - the number (1, 2, or 4) of y's, m's, and d's are what matters.
Albert says
It's in the first paragraph of thread: (There is a third way: use Adobe Acrobat's package feature. It makes a really nice PDF archive, if you own Acrobat.)
Diane Poremsky says
Oh - that is built into Acrobat - when the Acrobat addin is enabled, there will be a menu to create a PDF package, which is a collection of individual pdf files. It's great for creating an archive. It saves the selected messages and any attachments bundled together as individual pdf's with in one big pdf file. Selecting a bunch of messages and printing them as PDF creates one big PDF - a package creates individual pdf's within a big pdf.
Albert says
Hi Diane,
You mentioned there was a third option regarding the Adobe Acrobat feature. Can you provide more details?
Diane Poremsky says
Sorry, I don't recall in what context I said it and don't see it in a quick look over the comments.
Denny says
Hi Diane,
I have another problem with the script again. At first, it was works well for the first time. The next day, after i reboot my system, the script is no longer working. The rules is still there.
There is no error message. It just can't save the email to the folder.
Please advice is there any troubleshooting method?
Thanks.
Diane Poremsky says
Is macro security set to low / none? That is the usual reason why scripts aren't working.
Denny says
Hi Diane,
What should i do after go in to the references window? I totally know nuts on VBA.
Thanks in advance.
Diane Poremsky says
Locate Microsoft Word version.0 Object Library on the list and check it. If you have more than one listed, choose the one that is the same version as Outlook - usually the higher number. I added a screenshot of the dialog to the page.
Denny says
Hi,
I'm a noob in scripting.
I just copy and paste your comman and create the outlook rule.
When i trigger the rule, it the VBA will have compile error: User-defined type not defined.
Diane Poremsky says
Forgetting to do this will cause that error:
Don't forget to set a reference to the Word object library in Tools > References.
Albert says
Hi Diane,
Using the script mentioned above, where is the converted file saved at?
Regards,
Albert
Diane Poremsky says
These lines control that:
MyDocs = WshShell.SpecialFolders(16)
strToSaveAs = MyDocs & "\" & sName & ".pdf"
Specialfolders(16) is the user's Documents folder.
Ed van den Bogaard says
Removing the "as object" parts solved the problem.
Just out of curiosity: because tmpFileName and MyDocs are not dimmed in your code, I wonder if the issue I ran into is because of the different language version I use?
Thanks and regards,
Ed
Diane Poremsky says
i dont think your language has an affect. its good form to declare everything but its not always required.
Ed van den Bogaard says
Hi Diane,
The macro doesn't work in my Outlook 2010 (32 bit) on Windows 7 (64 bit). Both Outlook and Windows 7 are Dutch language versions.
First I get the error that tmpFileName and MyDocs are not defined as variables.
After insert
Dim tmpFileName As Object
Dim MyDocs As Object
the macro gives an "error 450" on the line
tmpFileName = tmpFileName & "\" & sName & ".mht"
Any idea what's causing the trouble?
Regards,
Ed van den Bogaard
Diane Poremsky says
They should be dimmed as string, not object. Either change it to string, or remove the as object part.
Richard Wilde says
Hi Diane, I assume this will work with outlook 2013 (365). My use case is to run a rule as an email comes in (can see from comments how this is possible) then save as PDF to disk then I would need to send this pdf as an attachment with the original email subject
Possible?
Thanks, great article by the way
Diane Poremsky says
It will work with Outlook 2013/365.
Rafael says
Hello Diane - is there any way to have the user pick the file name, if so, can the save as dialog open to a preset folder?
Diane Poremsky says
you need to call the open/save dialog. I'll see if i can find a code sample that does that.
Eugene says
Hello Diane,
I would like to save only 1st page of email and rename the file based on information found in the body of the text (SWIFT MT103). I have the following information in the email body.
"...
:32A:141128USD100000,00
...
"
[Value Date/Currency/Amount]
[YY MM DD CURR Amount]
I want to save the PDF file as "28112014" [DDMMYYYY]
If you could help adjust the code to get the email saved and renamed would be greatly appreciated.
Thanks,
Eugene
Diane Poremsky says
First page is easy: From:=1, To:=1,
Grabbing the date out requires regex. Samples are here: https://www.slipstick.com/developer/regex-parse-message-text/
All you need is a pattern to search for - this might work if the date is always 6 digits.
.Pattern = "[:](\w*)[:](\d){6}(\w*)" should = :32A:141128USD and M.SubMatches(1) should get just the date.
Eugene says
Hello Diane,
Thanks for the code. Is there a way to save only the 1st page of the email?
Many thanks
Diane Poremsky says
if you want to save only the first page of the message as a pdf, in this macro (which uses word to save the pdf), you would change From:=0, To:=0, to From:=1, To:=1,.
Dejan says
Hello Diane,
Is there a vba code to save .msg to .pdf, i have a code where it will extract e-mail from outlook and put it into a folder as .msg, I need vba code to convert it to .pdf, also I have a full version of adobe.
Thank you
Diane Poremsky says
I have a code sample here - https://www.slipstick.com/developer/code-samples/save-outlook-email-pdf/
themetalfox says
Hi Diane
Do you have an 'out of the box' Outlook 2013 script that can do the following for all emails in a certain folder?
Create a forwarded message
Delete all email addresses from text before forwarding
Delete any email signature before forwarding
Delete all hyperlinks completely before forwarding
Delete any text string beginning with http before forwarding
Forward email to a specific email address
I literally have hundreds of emails a day I have to forward but currently I have to forward these manually as for security reasons I have to manually delete all hyperlinks (including the text for the hyperlink itself) and email addresses. A script that does the above would be a legitimate godsend as I do not know how to code at all.
Hope you can help?
Diane Poremsky says
I don't have any that do all that -
#1/6 are simple (have code)
#2 can be more difficult - i might have code that can be tweaked to do it.
#3 if there is a way to define the signature - such as using "-- " to mark where it begins, yes. If the signature block is not defined, it's more difficult.
#4 difficult, not impossible. I don't think i have any code samples but word code to remove hyperlinks should work.
#5 a regex should do it.
Carrie Kelly says
Diane,
How would I change the title the .pdf is saved with?
The current email is titled CM FML Not 0000000
I would like to save the title as 00000000_FMLDOC_yyyyddmmhhss
Any thoughts on how I can do that with this code?
Diane Poremsky says
The name is set using this code:
sName = Item.Subject
ReplaceCharsForFileName sName, "-"
so you'd change the sName string. the date is set using Format(item.receivedtime, "yyyddmmhhss"). if the format is always 2 characters, space, 3 characters, space, digits, you can use instr, mid, and other functions to put it together.
FML: strdoc = mid(sName, 3,3)
0000's: strCode = right(sName, 7)
put that together for the subject:
strCode & "_" & strdoc & "DOC_" & strDate
if the strCode section length varies, you need to use mid and len to get it.
Renee SIms says
Can I change the My Docs in this code to save the email message to the same place I'm saving the attachments too? (from your other example)?
Diane Poremsky says
Yes, you can. The only thing that matters is that strToSaveAs is a valid path. How you get there is not important.
phan says
Is there a way rename the file if it exist to add (1), (2) .... at the end instead adding the time and date?
Thanks,
Diane Poremsky says
Yes, you'd use sName = sName & "(" & i & ")" to set the name. There are three options for numbering:
consecutive numbers for each attachment in a message. It resets to 1 with each message.
consecutive numbers during an outlook session - resets when outlook is closed and reopens.
consecutive numbers forever - use either a text file or registry to increment the number and pick up the next number after restarting or rebooting.
A sample using the registry is at https://www.poremsky.com/office/sequential-numbers-random-character-keywords/ - the text file method is at VBOffice.net and linked from that page.
To change restart at 1 when you restart outlook, use
Dim i as Long at the top of the page (outside of the macro)
then use
i = i + 1
before the filename is set.
richbmar says
Hi Diane, Thanks for the script version. It works very well. Would it be possible to delete the message from Outlook once the message is saved as a pdf? I am running the script from a rule on messages that do not have attachments. I would be very efficient if I could delete them automatically once they are saved as a .pdf.
(I am also very interested in a script that would save both the message and an associated attachment)
Regards,
Diane Poremsky says
You could delete the message - at the end, before Next obj, add item.delete
Wayne says
Very useful. What line do I need to modify to change the save location, to say 'D:\Save'
Diane Poremsky says
These lines do the save:
MyDocs = WshShell.SpecialFolders(16)
strToSaveAs = MyDocs & "\" & sName & ".pdf"
So change MyDocs to "D:\Save" - this ensures that anything to uses the MyDocs variable will have the correct path. If nothing else uses it, you could change strtoSaveas to "D:\Save\" & sName & ".pdf"
anthony houston says
I have been able to use this code successfully. I was wondering if it is possible to implement some additional code in the "Create a word object" portion. For instance, I need to delete the header (list of emails) so i tried implementing some code to delete them, but no success. Tried adding the following to delete the first 18 lines:
Selection.MoveDown Unit:=wdLine, Count:=18, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
Diane Poremsky says
It is possible, but you need to call the inspector. This macro has the basics - https://www.slipstick.com/developer/word-macro-apply-formatting-outlook-email/ - then you can use movedown and delete.
Mike says
Hi, its okay the windows finally appears in front of the windows. Now, i would like to know if its possible to save the email into the desktop instead of the documents.
Thank you very much you make it easier for me !! :)
Diane Poremsky says
That would be changed in SpecialFolders(16) - try SpecialFolders(10) for desktop.
Mike says
I run it from a button that i've installed in the ribbon.
Its supposed to work by there ? By the way thank you for answering me ! :)
Diane Poremsky says
Normally when you use a button, any dialog comes up on top. Actually, the macro saves it using the subject name in My Documents - you changed it to bring up the dialog. What code are you using to bring up the Save as dialog?
When I use browseforfolder function and replace the mydocs line with this:
MyDocs = WshShell.SpecialFolders(16)
MyDocs = BrowseForFolder("C:\Users\diane\documents\")
the dialog comes up on top.
Dave says
Save the email and all the attachments as a single PDF.
Diane Poremsky says
I'll see if i can put something together.
Bruce says
That would be great to have this. I am looking for something similar as well. Thanks!
Mike says
Hi, when I execute this macro the windows of "save as" is behind the other windows, can we use the Z-Order or Z-Indez command here ?
Diane Poremsky says
Are you running it from the VBA editor or using a button on the ribbon or the Macros list on the Developer tab? It should only come up in the background if you run it from the VBA Editor.
ahecht says
Were you able to create a script that includes the message and any attachments in a single pdf?
Diane Poremsky says
No, I haven't been able to get it working.
Diane Poremsky says
I think what we need to do is print to pdf and include the attachment in the same print...
Dave says
Hi Diane
This macro only exports the email contents and not the attachments.
Do you think it's possible to expand this macro to include a copy of the attachments as well into the same file?
Diane Poremsky says
I swear I replied to this earlier. :( Yes, you could. Do you want to print the attachment as a pdf or just save it with the pdf?
Jules says
I've copied across the code and inserted to Module 4 as a macro.
It is not visible int the Macro selector
All in accordance with May 10 2013 link nad made sure the name header was correct.
Definitely user error my end I'm sure.
Regards,
Diane Poremsky says
This line: Sub SaveMessageAsPDF(Item As Outlook.mailItem) means it only runs from another macro or a rule, it won't be listed in the macros list. If you run it manually (ie, from the macros list) you need to use the macro on the page.
Jules says
Diane, I've tried to use the outlook macro but with no luck.
I've copied the vba from the link but it is not visible in Macros.
Any assistance appreciated.
Diane Poremsky says
Did it have a name - Sub SaveMessageAsPDF()? I just noticed that was missing from the code. To run it manually, you'll use a name in that format. To run it from another macro (or in a rule) you'd use Sub SaveMessageAsPDF(Item As Outlook.mailItem) format for the name.
Adam says
Hi,
I wonder if it'd be possible to have this code run as a rule, but save as a .txt rather than a .pdf. This would presumably cut out the steps to open MS Word making the code a tad more simple?
I can't believe this functionality isn't built into Outlook as standard. It's a good job there are people like you providing the average user with some help.
Diane Poremsky says
I have a code sample for text - Save email message as text file.
to use it in a rule, change the sub title to
Sub SaveMailAsFile(Item As Outlook.mailItem)
and change oMail to item in the code.
Javier says
Dear Diane:
Your script is very very useful. Thank you very much for sharing.
If you allow me i would like to make a suggestion:
- The reason why the script is slow is because every iteration the Word Object is created and destroyed.
- Move the word object creation and destroy out of the loop. This way it will only create it once and re-use it for each file. That will improve the performance drastically.
Best regards.
Dustin Weld says
Can this MACRO be changed to run as a script so that it can be used in Outlook Rules?
Diane Poremsky says
Yes, it can be changed. Start with the name:
Sub SaveMessageAsPDF(Item As Outlook.mailItem)
Then remove the first 6 lines (3 dim, 2 set, For...) and the last 4 (Next obj and 3 Set's).
I posted a text file with the corrected code here