Getting Started with Outlook VBA
Like most of the Office programs, Microsoft Outlook 2000 and later versions includes Visual Basic Applications, where you can write your own code to automate Outlook. And, like most of the Office programs, there is no macro recorder. Fortunately, there are plenty of VBA samples here and elsewhere.
Here are the absolute basics for getting started with Outlook VBA:
- In Outlook 2000 to 2003, choose Tools | Macro | Security and set security to Medium. In Outlook 2007, the macro security settings are in the Tools | Trust Center dialog. Set macro security to Warn on all macros.
- Restart Outlook.
- Press Alt + F11 to bring up the VBA environment,
- Expand the Project Explorer at upper left.
- Double-click the built-in ThisOutlookSession module to open it. Accept the prompt to enable macros.
- Type or paste your code into the ThisOutlookSession module.
Here is a simple sample you can use to see if it's all working. It creates a new mail message with the subject "Hello World" and displays it:
To run a VBA macro from the VBA environment, press F5 or click the Run button on the toolbar. Or run it from the main Outlook window with Alt-F8. If you get an "enable macros" prompt, choose to enable.
About the Application Object
Application is an intrinsic object that represents the running Outlook application. To avoid security prompts , you should derive all Outlook objects in your code from this intrinsic Application object, as in this statement that creates a new mail message:
Set msg = Application.CreateItem(olMailItem)
For an example of how to get a "trusted" MailItem object derived from Application when writing a procedure for use with an Outlook "run a script" rule action, see:
If you want to write a macro that operates on either an open item or an item selected in a folder, you can add the GetCurrentItem() function to your VBA project. Just remember to change this statement:
Set objApp = CreateObject("Outlook.Application")
Set objApp = Application
so that it uses the intrinsic Application object.
To process all the items selected in Outlook's main window, first return the ActiveExplorer.Selection collection:
Set colSel = Application.ActiveExplorer.Selection
To perform some action on the currently open item, first return the ActiveInspector.CurrentItem object:
Set objItem = Application.ActiveInspector.CurrentItem
If you can't get VBA to run at all, see: