On my blog and on various messageboards such as VBA Express, I find myself using the same event code repeatedly. So here is the stock event code I use when someone asks "How do I do X automatically?"
This code is perfect for questions like
- How do I move messages automatically depending on the sender or subject?
- How do save new attachments to different folders?
- How do I open or print attachments depending on the time of day?
There are many other conditions as well, such as
- message importance
- the number or type of attachments
- specific words contained in the body
- whether you were CC'd or BCC'd
You can customize your event to handle any of these conditions and more.
All you need to do is cut and paste the code below into your ThisOutlookSession module in Outlook's VBIDE. (Press Alt+F11 to get there from Outlook.) Then customize to your liking. See the comments for the spots that you need to edit.
Private WithEvents Items As Outlook.Items Private Sub Application_Startup() Dim olApp As Outlook.Application Dim objNS As Outlook.NameSpace Set olApp = Outlook.Application Set objNS = olApp.GetNamespace("MAPI") ' (1) default Inbox Set Items = objNS.GetDefaultFolder(olFolderInbox).Items End Sub Private Sub Items_ItemAdd(ByVal item As Object) On Error Goto ErrorHandler Dim Msg As Outlook.MailItem ' (2) only act if it's a MailItem If TypeName(item) = "MailItem" Then Set Msg = item ' (3) do something here End If ProgramExit: Exit Sub ErrorHandler: MsgBox Err.Number & " - " & Err.Description Resume ProgramExit End Sub
You'll need to edit three spots:
- The folder you want to monitor for new messages;
- If you want a default folder, replace olFolderInbox with one of the olDefaultFolders Constants:
- olFolderDeletedItems – Deleted Items
- olFolderOutbox – Outbox
- olFolderSentMail – Sent Mail
- (olFolderInbox – Inbox)
- olFolderCalendar – Calendar
- olFolderContacts – Contacts
- olFolderJournal – Journal
- olFolderNotes – Notes
- olFolderTasks – Tasks
- olFolderDrafts – Drafts
For a non-default folder, you'll need to walk down the folder hierarchy and set a reference as follows:
' set a reference to Inbox\MyItems folder Set Items = objNS.Folders("Inbox").Folders("My Items").Items
' set a reference to Inbox\MyItems folder Set Items = objNS.GetDefaultFolder(olFolderInbox).Folders("My Items").Items
- Email messages
- Meeting requests
- Delegated/Assigned Tasks
which corresponds to
There are other types of items as well, such as TaskRequestAcceptItem (when someone accepts your task), or PostItem, which can also be added to any folder, and ReportItem, which is a system-generated delivery report. I've chosen to focus on the most common ones, however, but feel free to request additional samples using these objects.
This is left to your imagination. You can move messages to a folder, forward them to another recipient, or save attachments and run a macro on them. My blog has additional samples you can apply using this stock code.