Automating Outlook from a Visual Basic Applications

Microsoft Outlook Visual Basic

Automating Outlook from a Visual Basic Applications

   

Because Microsoft Outlook supports Automation, you can control Outlook from any program written with Microsoft Visual Basic. Automation provides a standard method for one application to access the objects, methods, properties, and events of other applications that support Automation.

The Outlook object model provides all of the functionality necessary to manipulate data stored in Outlook folders, and it provides the ability to control many aspects of the Outlook user interface.

To start an Outlook automation session, you can use either early or late binding. Late binding uses either the GetObject or the CreateObject function to initialize Outlook. For example, the following code sets an object variable to the Outlook Application object, which is the highest-level object in the Outlook object model. All automation code must first define an Outlook Application object to be able to access any other Outlook objects.

Dim objOL as Object
Set objOL = CreateObject("Outlook.Application")

To use early binding, you first need to set a reference to the Outlook object library. You can then use the following syntax to start an Outlook session.

Dim objOL as Outlook.Application
Set objOL = New Outlook.Application

Most programming solutions interact with the data stored in Outlook. Outlook stores all of its information in Messaging Application Programming Interface (MAPI) folders. After you set an object variable to the Outlook Application object, you will commonly set a Namespace object to refer to MAPI, as shown in the following example.

Set objOL = New Outlook.Application
Set objNS = objOL.GetNameSpace("MAPI")
Set objFolder = objNS.GetDefaultFolder(olFolderContacts)

Once you have set an object variable to reference the folder that contains the items you wish to work with, you use appropriate code to accomplish your task, as shown in the following example.

Sub CreateNewDefaultOutlookTask()
    Dim objOLApp As Outlook.Application
    Dim NewTask As Outlook.TaskItem
    ' Set the Application object
    Set objOLApp = New Outlook.Application
    ' You can only use CreateItem for default items
    Set NewTask = objOLApp.CreateItem(olTaskItem)
    ' Display the new task form so the user can fill it out
    NewTask.Display
End Sub