313800 - Programming samples that can reference items and folders in Outlook by using Visual Basic .NET

Programming samples that can reference items and folders in Outlook by using Visual Basic .NET

Относится к
This article was previously published under Q313800

SUMMARY

The Microsoft Outlook object model is generally used to access various types of items in folders. This article contains samples of the methods, the properties, and the objects that you can use to refer to Outlook items and Outlook folders by using Microsoft Visual Basic .NET.

IN THIS TASK

INTRODUCTION

This article describes the various methods, properties, and objects that you can use to refer to Microsoft Outlook items and folders when you are using Visual Basic .NET. This article also includes code samples that you can use to refer to the Outlook items and folders when you are using Visual Basic .NET.

back to the top

Create a new Visual Basic .NET console application

To use these code samples, you must create a new Visual Basic .NET console application:
  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. Under Project Types, click Visual Basic Projects.
  4. Under Templates, click Console Application, and then click OK.

    By default, Module1.vb is created.
  5. Add a reference to the Microsoft Outlook 10.0 Object Library. To do this, follow these steps:
    1. On the Project menu, click Add Reference.
    2. Click the COM tab, locate Microsoft Outlook 10.0 Object Library, and then click Select.
    3. In the Add References dialog box, click OK.
In the code window, you can see an empty Sub Main() procedure that you can use for the code samples:
Module Module1



    Sub Main()



    End Sub



End Module

					
Note When you use the Write method or the WriteLine method to write to the console, you can add a breakpoint to the End Sub line of the code so that you can read the console before the console closes.

back to the top

Reference existing folders

GetDefaultFolder method

Default folders are folders that exist at the same level as the Inbox and that receive incoming mail. If you have more than one Inbox in your profile, press CTRL+SHIFT+I to select the default Inbox. The default folders are the folders that most users work with regularly, such as the Calendar folder, the Contacts folder, and the Tasks folder. You can easily refer to these folders by using the GetDefaultFolder method. The GetDefaultFolder method takes one argument that defines the type of folder that you want to refer to. An Outlook object has an enumeration that you can select. This enumeration is defined in the Outlook.OlDefaultFolders enumeration type. The following example assigns the objFolder object variable to the default Contacts folder and then writes the name of the folder to the console window:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objFolder As Outlook.MAPIFolder

        objFolder = objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)

        Console.Write(objFolder.Name)

    End Sub

				
back to the top

Folders object

You can use the Folders object to refer to any folder that is visible in the Outlook folder list. This object is typically used to refer to an Exchange public folder or to any other folder that is not a default Outlook folder.

The following example demonstrates how to refer to a public folder that is named My Public Folder. Note that you typically start at the top-most folder and work your way down to the folder that you want to reference. Also note that the folder names are case-sensitive. The folder names must exactly match the folder names as they appear in the Outlook folders list.
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objFolder As Outlook.MAPIFolder = _

            objNS.Folders.Item("Public Folders")

        objFolder = objFolder.Folders.Item("All Public Folders")

        objFolder = objFolder.Folders.Item("My Public Folder")

        Console.Write(objFolder.Name)

    End Sub

				
back to the top

Parent property

If you already have a reference to an Outlook item or folder, you can use its Parent property to create a reference to the folder that contains the item or the folder. The following example returns the name of the parent folder for a particular item:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objMessage As Outlook._MailItem

        objMessage = objOutlook.CreateItem(Outlook.OlItemType.olMailItem)

        Dim objFolder As Outlook.MAPIFolder = objMessage.Parent

        Console.Write(objFolder.Name)

    End Sub

				
back to the top

GetSharedDefaultFolder method

You can use this method if another user has granted you permission to one of their default folders. You use the GetSharedDefaultFolder method as you use the GetDefaultFolder method, except that you must also specify the name of the user whose folder you want to reference. The following example first resolves the name of the other user to verify that the name is a valid name that can be used with the GetSharedDefaultFolder method:
GetSharedDefaultFolder:

    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objRecipient As Outlook.Recipient = _

            objNS.CreateRecipient("John Smith")

        If objRecipient.Resolve Then

            Dim objFolder As Outlook.MAPIFolder = _

                objNS.GetSharedDefaultFolder(objRecipient, _

                Outlook.OlDefaultFolders.olFolderCalendar)

            Console.Write(objFolder.Name)

        Else

            Console.Write("Recipient could not be resolved.")

        End If

    End Sub

				
back to the top

CurrentFolder method

This method is used to reference or to set the currently selected folder in an Outlook Explorer window. The following example uses the CurrentFolder method to set the Outlook Today page as the currently selected folder in the ActiveExplorer window:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objFolder As Outlook.MAPIFolder

        objFolder = objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

        objFolder = objFolder.Parent

        objOutlook.ActiveExplorer.CurrentFolder = objFolder

    End Sub

				
For additional information about how to access other people's folders, click the following article number to view the article in the Microsoft Knowledge Base:

290824 How to open someone else's calendar or other folder

back to the top

GetFolderFromID method

This method is typically used only in more complex solutions. These solutions keep track of both the StoreID field and the EntryID field of a folder so that the folder can be quickly referenced later.

For additional information about how to use the GetFolderFromID method, click the following article number to view the article in the Microsoft Knowledge Base:

293152 Programming with EntryIDs and StoreIDs

back to the top

Create and reference new folders

Folders.Add method

When you use the Add method of the Folders collection, you can create a new folder. The first argument specifies the name of the folder, and the second argument specifies the type of the folder. The following example adds a Personal Tasks subfolder to your default Tasks folder:
Folders.Add Method:

    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objTasks As Outlook.MAPIFolder = _

            objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderTasks)

        Dim objFolder As Outlook.MAPIFolder = _

            objTasks.Folders.Add("Personal Tasks", _

            Outlook.OlDefaultFolders.olFolderTasks)

    End Sub

				
back to the top

Create and reference new items

CreateItem method

The CreateItem method creates a new default Outlook item. If you want to create an item that is based on a custom form that you have created, use the Items.Add method that is described in the "Items.Add method" section. The CreateItem method is located off the top-level application object in the Outlook object model. This method takes only one argument. The argument is a constant that indicates the type of item to create:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objTask As Outlook._TaskItem

        objTask = objOutlook.CreateItem(Outlook.OlItemType.olTaskItem)

        objTask.Subject = "Test Item"

        objTask.Display()

    End Sub

				
back to the top

Items.Add method

When you use the Add method on the Items collection, you can create a new item that is based on any message class. The message class can be a default Outlook message class, such as the IPM.Contact message class, or the message class can be a message class for a custom form, such as the IPM.Contact.MyForm message class. To use the Items.Add method, you must first reference the folder where you want to create a new item.

The following example uses the Items.Add method to create a new item that is based on a custom contact form that is named MyForm:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objContacts As Outlook.MAPIFolder = _

             objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)

        Dim objItems As Outlook._Items = objContacts.Items

        Dim objContact As Outlook._ContactItem = objItems.Add("IPM.Contact.MyForm")

        objContact.Display()

    End Sub

				
The following example uses the Items.Add method to create a new item in the Contacts folder that is based on the default form for the folder. You can set the default form by changing the When posting to this folder, use setting in the folder Properties dialog box:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objContacts As Outlook.MAPIFolder = _

             objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)

        Dim objItems As Outlook._Items = objContacts.Items

        Dim objContact As Outlook._ContactItem = objItems.Add

        objContact.Display()

    End Sub

				
Note If you use the Items.Add method, the default form for the folder is not important. You can specify any valid message class as long as it has been published in the folder, in the personal forms library, or in the organizational forms library.

For additional information about message classes, click the following article numbers to view the articles in the Microsoft Knowledge Base:

290657 Working with form definitions and one-off forms

290659 OL2002: How to update existing items to use a new custom form

back to the top

CreateItemFromTemplate method

Use the CreateItemFromTemplate method to create a new item that is based on an Outlook template file (.oft) or on a message file (.msg) format. Because most forms are published in a folder or in a forms library, this method is not generally used. You may want to use this method if you are creating a Setup program to install forms for an Outlook solution. You typically do this for users who do not have network access or who typically work offline in Outlook. You may want to use the Setup program for the following reasons:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objContacts As Outlook.MAPIFolder = _

            objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)

        Dim objContact As Outlook._ContactItem = _

            objOutlook.CreateItemFromTemplate("C:\Contact.oft")

        Dim objForm As Outlook.FormDescription = objContact.FormDescription

        objForm.Name = "My Contact"

        objForm.PublishForm(Outlook.OlFormRegistry.olFolderRegistry, objContacts)

    End Sub

				
back to the top

Reference existing items

Items(i) and For Each...Next method

Typically, these methods are used to loop through all the items in a folder. The Items collection contains all the items in a particular folder, and you can specify which item to reference by using an index with the Items collection. This is typically used with the For loop construct.

The following example uses the Items(i) method to loop through all the contacts in the Contacts folder and to write the FullName field to the console window:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objContacts As Outlook.MAPIFolder = _

            objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)

        Dim objItems As Outlook._Items = objContacts.Items

        Dim iCount As Int16 = objItems.Count

        Dim i As Int16

        For i = 1 To iCount

            Console.WriteLine(objItems.Item(i).Fullname)

        Next

    End Sub

				
The following example uses the For Each...Next construct to loop through all the contacts in the Contacts folder and to write the FullName field to the console window:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objContacts As Outlook.MAPIFolder = _

            objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)

        Dim objItems As Object = objContacts.Items

        Dim objItem As Object

        For Each objItem In objItems

            Console.WriteLine(objItem.FullName)

        Next

    End Sub

				
back to the top

Items("This is the subject") method

You can also use the Items collection to specify a text string that matches the Subject field of an item. This method is not generally used. The following sample code displays an item in the Inbox with a subject line that contains "Please help on Friday!"
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objInbox As Outlook.MAPIFolder = _

            objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

        Dim objItems As Outlook._Items = objInbox.Items

        Dim objMessage As Outlook._MailItem = objItems.Item("Please help on Friday!")

        objMessage.Display()

    End Sub

				
back to the top

Find method

Use the Find method to search for an item in a folder based on the value of one of its fields. If the Find method is successful, you can then use the FindNext method to find additional items that meet the same criteria. The following example searches for high-priority tasks:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objFolder As Outlook.MAPIFolder = _

            objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderTasks)

        Dim objTasks As Outlook._Items = objFolder.Items

        Dim objTask As Outlook._TaskItem = _

            objTasks.Find("[Importance] = 'High'")

        If objTask Is Nothing Then

            MsgBox("Nothing Important. Go party!")

        Else

            MsgBox("You have something important to do!")

        End If

    End Sub

				
back to the top

Restrict method

The Restrict method is similar to the Find method, but instead of returning a single item, the Restrict method returns a collection of items that meet the search criteria. For example, you can use this method to find all contacts who work at the same company. The following example displays the FullName property of all the contacts who work at the A. Datum Corporation:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objNS As Outlook._NameSpace = objOutlook.Session

        Dim objFolder As Outlook.MAPIFolder = _

            objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)

        Dim objContacts As Outlook._Items = objFolder.Items

        Dim strCriteria As String = _

            "[CompanyName] = 'A. Datum Corporation'"

        Dim objADatumitems As Object = objContacts.Restrict(strCriteria)

        Dim objADatumitem As Outlook.ContactItem

        For Each objADatumitem In objADatumitems

            Console.WriteLine(objADatumitem.FullName)

        Next

    End Sub

				
back to the top

Selection method

The Selection method is used to return a collection of items based on the currently selected items in an Outlook Explorer window. The following example displays the subject for each item that is selected in the ActiveExplorer window:
    Sub Main()

        Dim objOutlook As Outlook._Application

        objOutlook = New Outlook.Application()

        Dim objSelection As Outlook.Selection = _

            objOutlook.ActiveExplorer.Selection

        Dim iCount As Int16 = objSelection.Count

        Dim i As Int16

        For i = iCount To 1 Step -1

            Console.WriteLine(objSelection.Item(i).Subject)

        Next

    End Sub

				
back to the top

GetItemFromID method

This method is typically used only in more complex solutions. These solutions keep track of both the StoreID field and the EntryID field of an item so that you can quickly reference the item later. For additional information about using the GetItemFromID method, click the following article number to view the article in the Microsoft Knowledge Base:

293152 Programming with EntryIDs and StoreIDs

back to the top

REFERENCES

For additional information about available resources and for answers to frequently asked questions about Outlook solutions, click the following article number to view the article in the Microsoft Knowledge Base:

287530 Questions about custom forms and Outlook solutions

back to the top

The information in this article applies to:



© 2002 Корпорация Microsoft. Все права защищены.