• Outlook User
  • New Outlook app
  • Outlook.com
  • Outlook Mac
  • Outlook & iCloud
  • Developer
  • Microsoft 365 Admin
    • Common Problems
    • Microsoft 365
    • Outlook BCM
    • Utilities & Addins

Saving All Messages to the Hard Drive Using VBA

Slipstick Systems

› Developer › Saving All Messages to the Hard Drive Using VBA

Last reviewed on August 29, 2018     151 Comments

Use this code to save messages with the date in the filename, retaining the Outlook file structure.

To save selected messages as PDF files, see Save Outlook email as a PDF

This code sample will save all messages in a specific Outlook folder (and any subfolders of the selected folder) in a folder you select on the hard drive. The messages will be in a subfolder of the selected folder, where the subfolder is named for the Outlook folder you selected.

Note: if you select a subfolder of a top-level folder, for example, a subfolder of the Inbox, folder named Inbox needs to exist in path on the hard drive.

The filename format is yyyymmdd_hhmm_subject.msg, as in:

20100422_0319_Inquiry.msg

The filename is set using this code:

StrFile = StrSaveFolder & StrReceived & "_" & StrName & ".msg"

Filenames are limited to 256 characters in length, with the subject trimmed if its too long.

Note that it can take some time to run if the folder contains a lot of messages. Allow about 2 seconds per message, or about 15 minutes for 400 messages.

VBA Code

Click in the code area, press Ctrl+A to select all, Ctrl+C to copy then paste into Outlook's VBA editor. Instructions on using the editor are at How to use Outlook's VBA Editor

Option Explicit
       Dim StrSavePath     As String

Sub SaveAllEmails_ProcessAllSubFolders()
      
    Dim i               As Long
    Dim j               As Long
    Dim n               As Long
    Dim StrSubject      As String
    Dim StrName         As String
    Dim StrFile         As String
    Dim StrReceived     As String
    Dim StrFolder       As String
    Dim StrSaveFolder   As String
    Dim StrFolderPath   As String
    Dim iNameSpace      As NameSpace
    Dim myOlApp         As Outlook.Application
    Dim SubFolder       As MAPIFolder
    Dim mItem           As MailItem
    Dim FSO             As Object
    Dim ChosenFolder    As Object
    Dim Folders         As New Collection
    Dim EntryID         As New Collection
    Dim StoreID         As New Collection
      
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set myOlApp = Outlook.Application
    Set iNameSpace = myOlApp.GetNamespace("MAPI")
    Set ChosenFolder = iNameSpace.PickFolder
    If ChosenFolder Is Nothing Then
GoTo ExitSub:
    End If
      
BrowseForFolder StrSavePath
         
    Call GetFolder(Folders, EntryID, StoreID, ChosenFolder)
      
    For i = 1 To Folders.Count
        StrFolder = StripIllegalChar(Folders(i))
        n = InStr(3, StrFolder, "\") + 1
        StrFolder = Mid(StrFolder, n, 256)
        StrFolderPath = StrSavePath & "\" & StrFolder & "\"
        StrSaveFolder = Left(StrFolderPath, Len(StrFolderPath) - 1) & "\"
        If Not FSO.FolderExists(StrFolderPath) Then
            FSO.CreateFolder (StrFolderPath)
        End If
          
        Set SubFolder = myOlApp.Session.GetFolderFromID(EntryID(i), StoreID(i))
        On Error Resume Next
        For j = 1 To SubFolder.Items.Count
            Set mItem = SubFolder.Items(j)
            StrReceived = Format(mItem.ReceivedTime, "YYYYMMDD-hhmm")
            StrSubject = mItem.Subject
            StrName = StripIllegalChar(StrSubject)
            StrFile = StrSaveFolder & StrReceived & "_" & StrName & ".msg"
            StrFile = Left(StrFile, 256)
            mItem.SaveAs StrFile, 3
        Next j
        On Error GoTo 0
    Next i
      
ExitSub:
      
End Sub
  
Function StripIllegalChar(StrInput)
    Dim RegX            As Object
      
    Set RegX = CreateObject("vbscript.regexp")
      
    RegX.Pattern = "[\" & Chr(34) & "\!\@\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
    RegX.IgnoreCase = True
    RegX.Global = True
      
    StripIllegalChar = RegX.Replace(StrInput, "")
      
ExitFunction:
    Set RegX = Nothing
      
End Function
  

Sub GetFolder(Folders As Collection, EntryID As Collection, StoreID As Collection, Fld As MAPIFolder)
    Dim SubFolder       As MAPIFolder
      
    Folders.Add Fld.FolderPath
    EntryID.Add Fld.EntryID
    StoreID.Add Fld.StoreID
    For Each SubFolder In Fld.Folders
        GetFolder Folders, EntryID, StoreID, SubFolder
    Next SubFolder
      
ExitSub:
    Set SubFolder = Nothing
      
End Sub
  
  
Function BrowseForFolder(StrSavePath As String, Optional OpenAt As String) As String
    Dim objShell As Object
    Dim objFolder '  As Folder

Dim enviro
enviro = CStr(Environ("USERPROFILE"))
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Please choose a folder", 0, enviro & "\Documents\")
StrSavePath = objFolder.self.Path

    On Error Resume Next
    On Error GoTo 0
      
ExitFunction:
    Set objShell = Nothing
      
End Function

How to use this macro

First: You need to have macro security set to low during testing. The macros will not work otherwise.

To check your macro security in Outlook 2010 or 2013, 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.

  1. Right click on Project1 and choose Insert > Module
  2. 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
Saving All Messages to the Hard Drive Using VBA was last modified: August 29th, 2018 by Diane Poremsky

Related Posts:

  • Save Messages and Attachments to a New Folder
  • Use VBA to open Outlook messages stored in the file system
  • Fix the Outlook Folder Type after Exporting an IMAP Account
  • browse for folder to save attachments
    How to use Windows File Paths in a Macro

About Diane Poremsky

A Microsoft Outlook Most Valuable Professional (MVP) since 1999, Diane is the author of several books, including Outlook 2013 Absolute Beginners Book. She also created video training CDs and online training classes for Microsoft Outlook. You can find her helping people online in Outlook Forums as well as in the Microsoft Answers and TechNet forums.

Subscribe
Notify of
151 Comments
newest
oldest most voted
Inline Feedbacks
View all comments

Pedro (@guest_220633)
September 27, 2023 3:49 am
#220633

Dear Diane, many thanks for this excellent Macro, it is working like a charm and it is actually very helpful. A question: is there any way to automate the process, like running the Macro every time Outlook starts or at a certain time every day ?

Thank you in advance

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Pedro
September 27, 2023 12:01 pm
#220635

Outlook doesn't have a timer, but you can use a reminder to trigger it.
https://www.slipstick.com/developer/code-samples/running-outlook-macros-schedule/

0
0
Reply
aleks (@guest_219941)
December 21, 2022 8:28 am
#219941

Thank you for a very useful and smoothly running macro!
Love peace and respect!

0
0
Reply
Kilimanj99 (@guest_218724)
September 14, 2021 12:58 pm
#218724

This script is great, exactly what I was looking for. Thank you! I will note I found 2 issues that I'll try to fix. You may already know about these. If you cancel when asked to select a save folder it will error out rather than handling the exception. If you select a folder in outlook to save and that folder is not a top level folder, ie InBox\NewFolder the script will error out saying the path does not exist. This looks to be because its trying to save in inbox\newfolder initially and hasnt yet created the inbox folder first so it cannot create the folder newfolder and thus it doesnt exist yet. Here's where that happens, I made a few mods so I'm not sure the line number, its around 40-45 and at this point strfolderpath = inbox\newfolder what it needs to do is create inbox then create newfolder in 2 seperate actions. If Not FSO.FolderExists(StrFolderPath) Then       FSO.CreateFolder (StrFolderPath)     End If Neither are a big deal to me, no impact, but thought I'd mention it. If you're looking for improvements it would be really cool if it gave a progress status of some sort. For me it just puts… Read more Âğ

0
0
Reply
Tammy (@guest_218622)
August 13, 2021 10:21 am
#218622

How can I modify the above to get items off a Microsoft exchange server? Code works as long as its not in exchange server.

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Tammy
August 14, 2021 9:22 pm
#218629

It should work with email in any account in Outlook. It won't work with Outlook on the web.

0
0
Reply
Duncan (@guest_218547)
July 20, 2021 10:25 am
#218547

I get the error "Run-time error '76': Path not found. "

Any ideas of how to fix this?

1
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Duncan
July 21, 2021 12:32 pm
#218553

At what point in the macro does it return this error? It means there is an error in the path - you can add one of these lines right before that line to see what it is using for the path. Which line you use depends on which line it errors on.
msgbox StrSaveFolder
or
msgbox StrFile

0
0
Reply
Xavier (@guest_219598)
Reply to  Diane Poremsky
August 5, 2022 10:28 am
#219598

hello, i tried to apply this but I keep receiving the error message.

0
0
Reply
sally (@guest_218298)
May 27, 2021 6:25 am
#218298

Hi Diane, so grateful for your work, but when i run it, is said the macros disables even after i changed the settings in trust centre to accept all macros. Would there be any way to fix it? thanks!

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  sally
May 28, 2021 9:29 am
#218305

This is after you restarted outlook? Are these new macros - or did you previously use them with a digital signature?

0
0
Reply
Selly (@guest_217553)
February 10, 2021 1:16 pm
#217553

Hello Diane,

it is a great work and very useful for me.
I am thankful for your work.
But i would like to choose also sub-folders to save the Emails in this folder to any other folder on the harddrive. Is it possible?

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Selly
February 11, 2021 12:59 am
#217555

So you want to save the email in just one folder to the hard drive? This one saves the selected messages to a folder of your choice.
Save Selected Email Message as .msg File (slipstick.com)

0
0
Reply
Selly (@guest_217559)
Reply to  Diane Poremsky
February 11, 2021 3:46 pm
#217559

No. I mean i want to choose and save sub-folders, not Parent folder. Is it possible?

0
0
Reply
Maros (@guest_215576)
July 10, 2020 11:11 am
#215576

Hi. I am working on archivation tool for Outlook. Only problem (or actual) is that I am not able to Save encrypted emails. Your script will skip such mails. It is not possible to extract ReceivedTime nor SenderName from such encrypted Items. I could not find solution for this anywhere on the internet. Do you think it is somehow possible? Thanks.

0
0
Reply

Visit Slipstick Forums.
What's New at Slipstick.com

Latest EMO: Vol. 28 Issue 27

Support Services

Do you need help setting up Outlook, moving your email to a new computer, migrating or configuring Office 365, or just need some one-on-one assistance?

Subscribe to Exchange Messaging Outlook






Our Sponsors

CompanionLink
ReliefJet
  • Popular
  • Latest
  • Week Month All
  • How to Remove the Primary Account from Outlook
  • Adjusting Outlook's Zoom Setting in Email
  • Move an Outlook Personal Folders .pst File
  • Save Sent Items in Shared Mailbox Sent Items folder
  • Remove a password from an Outlook *.pst File
  • Outlook: Web Bugs & Blocked HTML Images
  • This operation has been cancelled due to restrictions
  • Create rules that apply to an entire domain
  • Outlook Auto Account Setup: Encrypted Connection not available
  • Use PowerShell to get a list of Distribution Group members
  • How to Block Foreign Spam
  • Automatically Open New Outlook when Windows boots
  • Block External Content in New Outlook
  • Save Messages in New Outlook
  • Send Individual Messages when Sending Bulk Email
  • Centrally managed signatures in Office 365?
  • Create a rule to delete spam with no sender address
  • Open Outlook Folders using PowerShell or VBScript
  • Cannot add Recipients in To, CC, BCC fields on MacOS
  • Change Appointment Reminder Sounds
Ajax spinner

Newest Code Samples

Delete Old Calendar Events using VBA

Use PowerShell or VBA to get Outlook folder creation date

Rename Outlook Attachments

Format Images in Outlook Email

Set Outlook Online or Offline using VBScript or PowerShell

List snoozed reminders and snooze-times

Search your Contacts using PowerShell

Filter mail when you are not the only recipient

Add Contact Information to a Task

Process Mail that was Auto Forwarded by a Rule

Recent Bugs List

Microsoft keeps a running list of issues affecting recently released updates at Fixes or workarounds for recent issues in Outlook for Windows.

Outlook for Mac Recent issues: Fixes or workarounds for recent issues in Outlook for Mac

Office Update History

Update history for supported Office versions is at Update history for Office

Outlook Suggestions and Feedback

Outlook Feedback covers Outlook as an email client, including Outlook Android, iOS, Mac, and Windows clients, as well as the browser extension (PWA) and Outlook on the web.

Use Outlook.com Feedback for suggestions or feedback about Outlook.com accounts.

Other Microsoft 365 applications and services




Windows 10 Issues

  • iCloud, Outlook 2016, and Windows 10
  • Outlook Links Won’t Open In Windows 10
  • Outlook can’t send mail in Windows 10: error Ox800CCC13
  • Missing Outlook data files after upgrading Windows?

Outlook Top Issues

  • The Windows Store Outlook App
  • The Signature or Stationery and Fonts button doesn’t work
  • Outlook’s New Account Setup Wizard
  • Outlook 2016: No BCM
  • Exchange Account Set-up Missing in Outlook 2016

VBA Basics

How to use the VBA Editor

Work with open item or selected item

Working with All Items in a Folder or Selected Items

VBA and non-default Outlook Folders

Backup and save your Outlook VBA macros

Get text using Left, Right, Mid, Len, InStr

Using Arrays in Outlook macros

Use RegEx to extract message text

Paste clipboard contents

Windows Folder Picker

Custom Forms

Designing Microsoft Outlook Forms

Set a custom form as default

Developer Resources

Developer Resources

Developer Tools

VBOffice.net samples

SlovakTech.com

Outlook MVP David Lee

Repair PST

Convert an OST to PST

Repair damaged PST file

Repair large PST File

Remove password from PST

Merge Two Data Files

Sync & Share Outlook Data

  • Share Calendar & Contacts
  • Synchronize two computers
  • Sync Calendar and Contacts Using Outlook.com
  • Sync Outlook & Android Devices
  • Sync Google Calendar with Outlook
  • Access Folders in Other Users Mailboxes

Contact Tools

Data Entry and Updating

Duplicate Checkers

Phone Number Updates

Contact Management Tools

Diane Poremsky [Outlook MVP]

Make a donation

Mail Tools

Sending and Retrieval Tools

Mass Mail Tools

Compose Tools

Duplicate Remover Tools

Mail Tools for Outlook

Online Services

Calendar Tools

Schedule Management

Calendar Printing Tools

Calendar Reminder Tools

Calendar Dates & Data

Time and Billing Tools

Meeting Productivity Tools

Duplicate Remover Tools

Productivity

Productivity Tools

Automatic Message Processing Tools

Special Function Automatic Processing Tools

Housekeeping and Message Management

Task Tools

Project and Business Management Tools

Choosing the Folder to Save a Sent Message In

Run Rules on messages after reading

Help & Suggestions

Submit Outlook Feature Requests

Slipstick Support Services

Buy Microsoft 365 Office Software and Services

Visit Slipstick Forums.

What's New at Slipstick.com

Home | Outlook User | Exchange Administrator | Office 365 | Outlook.com | Outlook Developer
Outlook for Mac | Common Problems | Utilities & Addins | Tutorials
Outlook & iCloud Issues | Outlook Apps
EMO Archives | About Slipstick | Slipstick Forums
Submit New or Updated Outlook and Exchange Server Utilities

Send comments using our Feedback page
Copyright © 2023 Slipstick Systems. All rights reserved.
Slipstick Systems is not affiliated with Microsoft Corporation.

wpDiscuz

Sign up for Exchange Messaging Outlook

Our weekly Outlook & Exchange newsletter (bi-weekly during the summer)






Please note: If you subscribed to Exchange Messaging Outlook before August 2019, please re-subscribe.

Never see this message again.

You are going to send email to

Move Comment