To simplify and speed up the work with many mails, it is advisable to insert a few automatisms. This is the case, for example, if you receive a lot of emails of a certain type that you want to automatically assign to a certain subfolder.
Example 1: You get a lot of emails from your online shop with incoming orders and you want them to be automatically moved to a folder called “Orders“.
Example 2: You simply want to move certain selected emails from the inbox to an archive folder with one click.
Of course, you can also use Outlook’s built-in functions for creating automatic rules. The following screenshot shows where to find them.
However, there are certainly use cases where this is not quite the appropriate tool of first choice, e.g. if you want to banish all marked emails to a certain subfolder with one click. Or if you already have another VBA macro, e.g. for automatically replying to an email, and in the same macro you want to mark the source mail as read and then move it from the inbox somewhere else.
VBA code: Move email to subfolder
The following screenshot and code example show how to move one or more selected emails to a subfolder of the Inbox.
This code example loops through all the emails selected in Outlook in the For Each loop and then moves them to a specified folder (“All Mails”), which is a subfolder of the Inbox.
Public Sub MoveMail() Dim olItem As Outlook.MailItem Dim objNS As Outlook.NameSpace Dim objFolder As Outlook.MAPIFolder Dim destFolder As Outlook.Folder 'Define the destination folder; in this case it is "All Mails", a subfolder of "Inbox". Set objNS = GetNamespace("MAPI") Set objFolder = objNS.Folders.GetFirst ' folder of the current mailbox. Set objFolder = objFolder.Folders("Inbox") Set destFolder = objFolder.Folders("All Mails") 'Move all selected emails to the defined subfolder. For Each olItem In Application.ActiveExplorer.Selection olItem.Move destFolder Next olItem End Sub
To get the object for the subfolder, you first have to define the Mapi namespace (GetNamespace(“MAPI”)). There you determine the relevant mailbox with objNS.Folders.GetFirst. We use GetFirst here because the relevant mailbox is in the first place in Outlook. If you have several mailboxes, you can either navigate to them with GetNext or address them directly via the index using .Item(number).
Then define the inbox as a folder and access its folder array to define the appropriate subfolder of the inbox. This is then the destination folder where the selected e-mails are to be moved to.
Please note that for the code to work, various references must be activated under References.