Ten Tips for Microsoft Outlook Developers (November 2002)

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

 

Bill Jacob and Frank C. Rice
Microsoft Corporation

November 2002

Applies to:
    Microsoft® Outlook® 2002

Summary: Learn Microsoft Outlook programming tips to accomplish such tasks as programmatically retrieving all recurring appointments, searching a folder tree using keywords, opening a form from a toolbar button, and more. (40 printed pages)

Contents

Programmatically Set Journaling for All Contacts
Retrieve All Recurring Appointments with VBA Code
Programmatically Update Company Names
Programmatically Search a Folder Tree
Programmatically Import Outlook Items from Microsoft Access
Tips for Printing Forms
Open a Form from a Toolbar Button
Create a Custom Rule Using VBA
Working Successfully with Collections
Programming Examples for Referencing Items and Folders

Programmatically Set Journaling for All Contacts

Microsoft® Outlook® journals can be used to log and track information such as the amount of time a person or workgroup spends on a particular task or with a customer. The following tip provides a Microsoft Visual Basic® for Applications (VBA) macro that you can use to programmatically change all of your contacts so that they are automatically set to journal.

The default setting for journaling contact items is disabled. If you create contacts and then decide to enable journaling for these contacts, set the journal option for each contact:

  1. On the Tools menu, click Options.

  2. On the Preferences tab, click Journal Options.

  3. In the For these contacts box, click each contact for which you want to enable journaling (see Figure 1).

    Aa155699.odc_novoltips01(en-us,office.10).gif

    Figure 1. Journal Options dialog box

If you have a large number of contacts and you want to enable journaling for all of them, it may be more efficient to programmatically change all of the contacts with a macro.

To create the SetAllContactsToJournal macro

  1. On the Tools menu, point to Macro, and then click Macros.

  2. In the Macro Name box, type SetAllContactsToJournal (no spaces), and then click Create. The Visual Basic Editor starts and automatically creates a subroutine for you.

  3. Type or paste the following lines of code:

    Sub SetAllContactsToJournal()
       Dim objContactsFolder As Outlook.MAPIFolder
       Dim objContacts As Outlook.Items
       Dim objContact As Object
       Dim iCount As Integer
    
       ' Specify which contact folder to work with
       Set objContactsFolder = Session.GetDefaultFolder(olFolderContacts)
       Set objContacts = objContactsFolder.Items
    
       iCount = 0
    
       ' Process the changes
       For Each objContact In objContacts
          If TypeName(objContact) = "ContactItem" Then
             If objContact.Journal = False Then
                objContact.Journal = True
                objContact.Save
                iCount = iCount + 1
             End If
          End If
       Next
    
       MsgBox "Number of contacts updated:" & Str$(iCount)
    
       ' Clean up
       Set objContact = Nothing
       Set objContacts = Nothing
       Set objContactsFolder = Nothing
    End Sub
    
  4. On the File menu, click Close and Return to Microsoft Outlook.

To use the SetAllContactsToJournal macro

  1. On the Tools menu, point to Macro, and then click Macros.

  2. Click SetAllContactsToJournal, and then click Run.

  3. A dialog box appears that tells you the number of contacts that were updated (see Figure 2).

    Aa155699.odc_novoltips02(en-us,office.10).gif

    Figure 2. Number of contacts updated dialog box

Notes

  • It may take a while to process the items in your Contacts folder.

  • While your contacts are being updated, the mouse pointer does not change to an hourglass to indicate that Outlook is running the macro. The Outlook object model does not support changing the mouse pointer in this manner.

  • You can assign the macro to a button if you use this macro often. For additional information on assigning this macro to a toolbar button, see the Microsoft Knowledge Base article OL2002: How to Assign a Macro to a Toolbar Button.

  • The sample code only works with the default Contacts folder. If you want it to work with any contacts folder, locate the following line of code:

    Set objContactsFolder = Session.GetDefaultFolder(olFolderContacts)
    

    and change it to:

    Set objContactsFolder = Outlook.ActiveExplorer.CurrentFolder
    
  • For information on referencing a Contacts folder in a different location, see the Referencing Existing Folders section of the Programming Examples for Referencing Items and Folders tip in this article.

Retrieve All Recurring Appointments with VBA Code

When using code to retrieve a set of calendar appointments in Outlook, by default, you can only retrieve the first instance of a recurring appointment. This occurs because the recurring appointments are not automatically included in the collection of appointment items. You can overcome this by setting the collection's IncludeRecurrences property to True.

For example, you can create a recurring appointment, such as a meeting that occurs every Monday and then using Visual Basic Scripting Edition (VBScript) or VBA code, do either of the following:

  • Use the entire Items collection to access all of the appointments.

    —Or—

  • Use the Restrict method to retrieve a subset of the appointments.

Assume, for instance, a recurring appointment was originally created on the first Monday in January and the appointment was set to recur on every Monday thereafter. If you do not use the IncludeRecurrences property, the only appointment in January to be returned would be the first Monday. Subsequently, if you retrieve the appointments in February, none of the recurring appointments are retrieved.

When programmatically referring to a group of appointments, these items are part of the Items collection object. Once you have set an object variable to the entire collection of items, you can then use the IncludeRecurrences property to optionally include all of the recurring appointments. Next, you would typically use the Restrict method if you want to use a subset of the entire collection. Then you could optionally sort the collection.

The following VBA example assumes you have already set up one recurring appointment in your calendar and that you have the Calendar folder selected. Because it does not use the Restrict method, it will return all appointments in the Calendar.

To create the GetRecurrences macro

  1. On the Tools menu, point to Macro, and then click Macros.

  2. In the Macro Name box, type GetRecurrences (no spaces), and then click Create. The Visual Basic Editor starts and automatically creates a subroutine for you.

  3. Type or paste the following lines of code:

    Sub GetRecurrences()
       Set myOlApp = New Outlook.Application
    
       ' Set myItems to all of the items in the folder. The Calendar
       ' folder must be selected before running this code.
       Set myItems = myOlApp.ActiveExplorer.CurrentFolder.Items
    
       ' Set the IncludeRecurrences property to make sure all of the
       ' recurring appointments are also included in the collection.
       myItems.IncludeRecurrences = True
    
       ' Sort the collection based on the start of the appointment.
       myItems.Sort "[Start]"
    
       ' Display one of the recurring appointments which have 
       ' been included.
       MsgBox "The fifth instance of the recurring appointment " & _
          "occurs on:" & myItems.Item(5).Start
    End Sub
    
  4. On the File menu, click Close and Return to Microsoft Outlook.

To use the GetRecurrences macro

  1. On the Tools menu, point to Macro, and then click Macros.

  2. Click GetRecurrences, and then click Run.

  3. A dialog box appears indicating the data and time of the fifth recurring appointment (see Figure 3).

    Aa155699.odc_novoltips03(en-us,office.10).gif

    Figure 3. Fifth recurring appointment notification dialog box

Programmatically Update Company Names

You can use Outlook VBA to change the company name for many contacts without having to manually open each contact. This solution is useful, for example, if a company changes its name and you have many contacts for that particular company.

To create the ChangeCompanyName macro

  1. On the Tools menu, point to Macro, and then click Macros.

  2. In the Macro Name box, type ChangeCompanyName (no spaces), and then click Create. This starts the Visual Basic Editor and automatically creates a subroutine for you.

  3. Type or paste the following code:

    Sub ChangeCompanyName()
       Dim objContactsFolder As Outlook.MAPIFolder
       Dim objContacts As Outlook.Items
       Dim strOldCo As String
       Dim strNewCo As String
       Dim objContact As Object
       Dim iCount As Integer
    
       ' Specify which contact folder to work with
       Set objContactsFolder = Session.GetDefaultFolder(olFolderContacts)
       Set objContacts = objContactsFolder.Items
    
       ' Prompt for old and new company names
       strOldCo = InputBox("Enter the old company name.")
       strNewCo = InputBox("Enter the new company name.")
    
       iCount = 0
    
       ' Process the changes
       For Each objContact In objContacts
          If TypeName(objContact) = "ContactItem" Then
             If objContact.CompanyName = strOldCo Then
                objContact.CompanyName = strNewCo
                objContact.Save
                iCount = iCount + 1
             End If
          End If
       Next
    
       MsgBox "Number of contacts updated:" & Str$(iCount)
    
       ' Clean up
       Set objContact = Nothing
       Set objContacts = Nothing
       Set objContactsFolder = Nothing
    End Sub
    
  4. On the File menu, click Close and Return to Microsoft Outlook.

To use the ChangeCompanyName macro

  1. On the Tools menu, point to Macro, and then click Macros.
  2. Click the ChangeCompanyName macro, and then click Run.
  3. The procedure prompts you for the old and then the new company names. Type in the names and click OK in each dialog box.
  4. Once processing is complete, a dialog box appears telling you how many contacts have been updated.

Notes

  • It may take a while to process the items in the folder.

  • While the contacts are being updated, the mouse pointer does not change to an hourglass to indicate that Outlook is running the macro. The Outlook object model does not support changing the mouse pointer in this manner.

  • You can assign the macro to a toolbar button if you use this macro often. For additional information on assigning this macro to a toolbar button, see the Microsoft Knowledge Base article OL2002: How to Assign a Macro to a Toolbar Button.

  • The sample code only works with the default Contacts folder. If you want it to work with any contacts folder, locate the following line of code:

    Set objContactsFolder = Session.GetDefaultFolder(olFolderContacts)
    

    and change it to:

    Set objContactsFolder = Outlook.ActiveExplorer.CurrentFolder
    
  • For information on referencing a Contacts folder in a different location, see the Referencing Existing Folders section of the Programming Examples for Referencing Items and Folders tip later in this article.

Programmatically Search a Folder Tree

This tip provides a code sample that shows how to programmatically search for items that contain a specific string in the Subject field. This procedure searches a selected folder and all of its subfolders.

Notes

  • The following sample code is designed for Outlook VBA. To use this sample in Visual Basic or other Microsoft Office programs, verify that the Microsoft Outlook 10.0 Object Library is referenced, and then change the following line of code:

    Set olApp = Application
    

    to:

    Set olApp = CreateObject("Outlook.Application")
    
  • The sample code uses the PickFolder method to prompt for the folder to search.

To create the WalkFolders macro

  1. On the Tools menu, point to Macro, and then click Macros.

  2. In the Macro Name box, type WalkFolders, and then click Create. This starts the Visual Basic Editor and automatically creates a subroutine for you.

  3. Type the following two statements into the Declarations section of the code window:

    Dim strSearchString As String
    Dim lCountOfFound As Long
    

    **Note   **You can move to the Declarations section by clicking (Declarations) in the Procedure drop-down box located in the upper right of the code window.

  4. Type or paste the following code:

    Sub WalkFolders()
       Dim olApp As Outlook.Application
       Dim olSession As Outlook.NameSpace
       Dim olStartFolder As Outlook.MAPIFolder
       Dim strPrompt As String
    
       'Initialize count of folders searched
       lCountOfFound = 0
    
       ' Get a reference to the Outlook application and session.
       Set olApp = Application
       Set olSession = olApp.GetNamespace("MAPI")
    
       ' Allow the user to input the search string.
       strPrompt = "Enter the search string to be found in the subject:"
       strSearchString = InputBox(strPrompt)
    
       If strSearchString <> "" Then
    
          ' Allow the user to pick the folder in which to start the search.
          Set olStartFolder = olSession.PickFolder
    
          ' Check to make sure user didn't cancel PickFolder dialog.
          If Not (olStartFolder Is Nothing) Then
             ' Start the search process.
             ProcessFolder olStartFolder
             MsgBox CStr(lCountOfFound) & " messages were found."
          End If      
       End If
    End Sub
    
    Sub ProcessFolder(CurrentFolder As Outlook.MAPIFolder)
       Dim i As Long
       Dim olNewFolder As Outlook.MAPIFolder
       ' Late bind this object variable, 
       ' since it could be various item types
       Dim olTempItem As Object
    
       ' Loop through the items in the current folder.
       ' Looping through backwards in case items are to be deleted,
       ' as this is the proper way to delete items in a collection.
       For i = CurrentFolder.Items.Count To 1 Step -1
    
          Set olTempItem = CurrentFolder.Items(i)
    
          ' Check to see if a match is found
          If InStr(1, olTempItem.Subject, strSearchString, 0) > 0 Then
    
             ' The following are examples of what you can do:
             ' 1. To notify that message was found, uncomment the line
             ' and run the procedure.
             ' MsgBox "Found message with subject: " & olTempItem.Subject
             '
             ' 2. To delete the item:
             ' olTempItem.Delete
             '
             ' 3. To move the item:
             '    NOTE: You need to first define olDestFolder
             ' olTempItem.Move olDestFolder
             '
             lCountOfFound = lCountOfFound + 1
          End If
       Next
    
       ' Loop through and search each subfolder of the current folder.
       For Each olNewFolder In CurrentFolder.Folders
          If olNewFolder.Name <> "Deleted Items" Then
             ProcessFolder olNewFolder
          End If
       Next
    End Sub
    
  5. In the ProcessFolder subroutine, uncomment one of the statements below the numbered explanations. For example, to test the procedure, you might uncomment the statement:

    MsgBox "Found message with subject: " & olTempItem.Subject
    
  6. On the File menu, click Close and Return to Microsoft Outlook.

To use the WalkFolders macro

  1. On the Tools menu, point to Macro, and then click Macros.
  2. Click the WalkFolders macro, and then click Run.
  3. The procedure prompts you for the search string. Type in the search string and click OK.
  4. Next, you are prompted to select the folder to search. Click a folder and click OK.
  5. Once processing is complete and the search string has been located in one or more of the folders, dialog box(es) appear informing you of the subject line containing the search string.
  6. And finally, a dialog box is displayed indicating the total number of messages that contained the search string in their subject line.

If this procedure is useful to you, you might want to assign it to a button on the toolbar. For information on assigning this macro to a toolbar button, see the Microsoft Knowledge Base article OL2002: How to Assign a Macro to a Toolbar Button.

Programmatically Import Outlook Items from Microsoft Access

This tip provides sample code for creating Outlook contacts from information stored in a Microsoft® Access® database.

The Import and Export features in Outlook do not allow you to import or export information in user-defined fields (or properties). To import information into these fields, you need a programming solution that uses VBA to convert the information.

The sample code in this tip specifically converts information from Access into newly-created Outlook contacts, using Data Access Objects (DAO). With modifications, you can use this code as a basis for creating other types of Outlook items, such as appointments, notes, tasks, and so forth.

Programming Considerations

  • The following sample code uses the Northwind sample database which is included with Access 2002. If you installed Office to a location other than the default, you will need to change the path to the database in the sample code.
  • You may need to set a reference to the Microsoft Outlook 10.0 Object Library, the Microsoft DAO 3.6 Object Library, and the Microsoft Office 10.0 Object Library unless already set. To do this, open the Visual Basic Editor, and then click References on the Tools menu.
  • The field or data types used in this example are Text in both Access and Outlook. To convert other types of fields, you must modify the code appropriately.
  • The contacts are automatically placed in the default Contact folder, which is at the same level as the Inbox.
  • The CreateItem method used in this example creates a new Outlook contact using the default form for the default contact folder. If you created a custom Outlook Contact form, you must set the MessageClass field for each item to the name of your custom form.

To create the ExportAccessContactsToOutlook macro

  1. On the Tools menu, point to Macro, and then click Macros.

  2. In the Macro Name box, type ExportAccessContactsToOutlook (no spaces), and then click Create. This starts the Visual Basic Editor and automatically creates a subroutine for you.

  3. Type or paste the following code:

    Sub ExportAccessContactsToOutlook()
       ' Set up DAO Objects.
       Dim oDataBase As DAO.Database
       Dim rst As DAO.Recordset
       Set oDataBase = OpenDatabase _
          ("c:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb")
       Set rst = oDataBase.OpenRecordset("Customers")
    
       ' Set up Outlook Objects.
       Dim ol As New Outlook.Application
       Dim olns As Outlook.Namespace
       Dim cf As Outlook.MAPIFolder
       Dim c As Outlook.ContactItem
       Dim Prop As Outlook.UserProperty
    
       Set olns = ol.GetNamespace("MAPI")
       Set cf = olns.GetDefaultFolder(olFolderContacts)
    
       With rst
          .MoveFirst
    
          ' Loop through the Microsoft Access records.
          Do While Not .EOF
    
             ' Create a new Contact item.
             Set c = ol.CreateItem(olContactItem)
    
             ' Specify which Outlook form to use.
             ' Change "IPM.Contact" to "IPM.Contact.<formname>" if you've
             ' created a custom Contact form in Outlook.
             c.MessageClass = "IPM.Contact"
    
             ' Create all built-in Outlook fields.
             If ![CompanyName] <> "" Then c.CompanyName = ![CompanyName]
             If ![ContactName] <> "" Then c.FullName = ![ContactName]
    
             ' Create the first user property (UserField1).
             Set Prop = c.UserProperties.Add("UserField1", olText)
    
             ' Set its value.
             If ![CustomerID] <> "" Then Prop = ![CustomerID]
    
             ' Create the second user property (UserField2).
             Set Prop = c.UserProperties.Add("UserField2", olText)
    
             ' Set its value and so on....
             If ![Region] <> "" Then Prop = ![Region]
    
             ' Save and close the contact.
             c.Save
             c.Close olDiscard
             .MoveNext
          Loop
       End With
    End Sub
    
  4. On the File menu, click Close and Return to Microsoft Outlook.

To use the ExportAccessContactsToOutlook macro

  1. On the Tools menu, point to Macro, and then click Macros.
  2. Click the ExportAccessContactsToOutlook macro, and then click Run.
  3. Once processing is complete, a list of contacts from the Northwind sample database is saved to the Contacts folder.

In addition to the information provided here, there is more sample code and a whitepaper titled Microsoft Office 97 Cross-Application Automation Samples with more information available on the MSDN site.

Tips for Printing Forms

When printing an Outlook form with a specific format, there doesn't seem to be many options available. Outlook can only print forms with the options that are available in the Print window. While you can customize the Print Style settings using the various options Outlook provides in its user interface, you cannot alter the basic way that Outlook prints form by using custom Print Styles. Additionally, the Outlook object model does not provide programmers with ways of directly changing the print format of a form.

To overcome some of these limitations, the following methods provide an overview of possible approaches you can use. These approaches should be evaluated based on factors such as:

  • Whether you are using a custom form or would consider using one to enable additional functionality.
  • Whether you need a custom print format or just want to print the form exactly as it appears on the screen.
  • Whether you have an adequate programming background. If you are familiar with programming in VBA, you should have little problem developing a solution. If not, you may want to obtain the services of a developer who can provide the solution.

Method 1: Use ALT+PRINT SCREEN

If you want to print a form as it appears on the screen without developing a VBA solution, you can use the ALT+PRINT SCREEN key sequence to copy the image of the form to the clipboard. You can then paste the contents of the clipboard into another program and print it.

To use Microsoft Word to print an image of an existing form

  1. With the Outlook form displayed, press ALT+PRINT SCREEN.
  2. Switch to or start Word.
  3. Make sure you have a new document open. You may want to reduce the margins of the document to allow more room for the image to fit on the page:
    1. On the File menu, click Page Setup, and then click the Margins tab.
    2. Under Margins, select the options you want.
  4. On the Edit menu, click Paste.
  5. Resize the image as appropriate:
    1. Click the image once to select it.
    2. On the Format menu, click Picture.
    3. Click the Size page of Format Picture.
    4. On the Size tab, set the Height and Width of the picture.
  6. To print the document, on the File menu, click Print.

Method 2: Use VBScript to Automate the ALT+PRINT SCREEN Method

If you want to print a form as it appears on the screen and would consider using a custom Outlook form that contains custom programming code, you can use VBScript to automate Method 1. The end result will be that you can press ALT+PRINT SCREEN and then click a button on the form to print it. You must add a Print button to the form to do this.

To create the custom form

  1. Open your form.

  2. On the Tools menu, point to Forms, and then click Design This Form. Click the (P.2) page of the form.

  3. On the Form menu, click Control Toolbox. Drag a CommandButton control onto the P.2 page of the form.

  4. Right-click the control and then click Properties.

  5. On the Display tab, set the Name to cmdPrint and the Caption to Print. Click OK and then close the Control ToolBox.

  6. On the Form menu, click View Code.

  7. Enter the following VBScript code into the Script Editor and then close the Script Editor:

    Sub cmdPrint_Click()
       Set oWordApp = CreateObject("Word.Application")
       If oWordApp Is Nothing Then
          MsgBox "Couldn't start Word."
       Else
          Dim oWordApp
          Dim oWordDoc
          Dim oBMs
          Dim bolPrintBackground
    
          ' Open a new document
          Set oDoc = oWordApp.Documents.Add
    
          ' Set a page setup object variable
          Set oPS = oDoc.PageSetup
    
          ' Reduce the margins to .5" (36 points)
          oPS.TopMargin = 36
          oPS.BottomMargin = 36
          oPS.LeftMargin = 36
          oPS.RightMargin = 36
    
          ' Paste in the screen shot
          oWordApp.Selection.Paste
    
          ' Center the screen shot
          Const wdAlignParagraphCenter = 1
          oDoc.Paragraphs(1).Alignment = wdAlignParagraphCenter
    
          ' Get the current Word setting for background printing
          bolPrintBackground = oWordApp.Options.PrintBackground
    
          ' Turn background printing off
          oWordApp.Options.PrintBackground = False
    
          ' Print the Word document
          oDoc.PrintOut
    
          ' Restore previous setting
          oWordApp.Options.PrintBackground = bolPrintBackground
    
          ' Close and don't save changes to the document
          Const wdDoNotSaveChanges = 0
          oDoc.Close wdDoNotSaveChanges
    
          ' Close the Word instance
          oWordApp.Quit
    
          ' Clean up
          Set oPS = Nothing
          Set oDoc = Nothing
          Set oWordApp = Nothing
       End If
    End Sub
    
  8. On the Tools menu, point to Forms, and then click Publish Form. The default is to store the Contact form in your Contacts folder.

  9. Type Print Test as the Display Name and then click Publish.

  10. Close and do not save changes to the form.

To test the form

  1. On the Actions menu, click New Print Test.
  2. Press ALT+PRINT SCREEN.
  3. Click the P.2 page of the form and click Print.

Method 3: Generate a Custom Report

If you want to create a custom printout, or avoid having users press ALT+PRINT SCREEN, you can create a Word template that contains form fields and then have Outlook automatically transfer fields from an Outlook item into the template. With this method, Word will handle all of the formatting and printing.

**Note   **You may want to use another program, such as Microsoft® Excel®, depending on the required format of the printout and your programming ability.

To create the sample Word template

  1. Open a new document in Word.
  2. On the View menu, point to Toolbars and then click Forms.
  3. Click the Text Form Field button on the Forms toolbar to insert a form field.
  4. Press ENTER twice and then click the Text Form Field button again to insert a second form field. The form fields have default bookmark names of Text1 and Text2, respectively
  5. Click the Protect Form button on the Forms toolbar to protect the template.
  6. On the File menu, click Save As.
  7. Change the Save As Type setting to Document Template, change the Save In setting to (C:), type MyForm as the name of the template and then click Save.
  8. Close the template.

To create the Outlook form

  1. Open a new Contact form. On the Tools menu, click Forms and then click Design This Form. Click the (P.2) page of the form.

  2. On the Form menu, click Control Toolbox.

  3. Drag a CommandButton control onto the P.2 page of the form. Right-click the control and then click Properties.

  4. On the Display tab, set the Name to cmdPrint and the Caption to Print.

  5. Click OK and then close the Control ToolBox.

  6. On the Form menu, click View Code.

  7. Enter the following VBScript code into the Script Editor and then close the Script Editor:

    Sub cmdPrint_Click()
       Set oWordApp = CreateObject("Word.Application")
       If oWordApp Is Nothing Then
          MsgBox "Couldn't start Word."
       Else
          Dim oWordApp
          Dim oWordDoc
          Dim bolPrintBackground
    
          ' Open a new document
          Set oDoc = oWordApp.Documents.Add("C:\MyForm.dot")
    
          ' Set the first bookmark to the contact's full name
          oDoc.FormFields("Text1").Result = CStr(Item.FullName)
    
          ' Set the second bookmark to the contact's birthday
          oDoc.FormFields("Text2").Result = CStr(Item.Birthday)
    
          ' If the form contains user-defined fields, you can use
          ' the following syntax to transfer the contents of a
          ' user-defined field (FieldName) to Word:
          ' strMyField = Item.UserProperties.Find("FieldName")
          ' oDoc.FormFields("Text3").Result = strMyField
    
          ' Get the current Word setting for background printing
          bolPrintBackground = oWordApp.Options.PrintBackground
    
          ' Turn background printing off
          oWordApp.Options.PrintBackground = False
    
          ' Print the Word document
          oDoc.PrintOut
    
          ' Restore previous setting
          oWordApp.Options.PrintBackground = bolPrintBackground
    
          ' Close and don't save changes to the document
          Const wdDoNotSaveChanges = 0
          oDoc.Close wdDoNotSaveChanges
    
          ' Close the Word instance
          oWordApp.Quit
    
          ' Clean up
          Set oDoc = Nothing
          Set oWordApp = Nothing
       End If
    End Sub
    
  8. On the Tools menu, point to Forms, and then click Publish Form. The default is to store the Contact form in your Contacts folder.

  9. Type Send Fields as the Display Name and then click Publish.

  10. Close and do not save changes to the form just created.

To test the form

  1. Click the Contacts folder.
  2. On the Actions menu, click New Send Fields.
  3. Enter a full name for the contact and on the Details page of the form, enter a birth date.
  4. Click Yes at the prompt to save the form.
  5. Click the P.2 page of the form and click Print.

The contact's full name and birthday will be printed. You can customize the Word template to suit your needs.

Open a Form from a Toolbar Button

This tip explains how to use VBA to open a custom Outlook form directly from the Outlook toolbar. First, create a VBA macro that opens a custom form. Then, assign the macro to a toolbar button or a menu so that the form can be easily opened.

**Note   **You cannot use the code in this sample to open forms created using the Exchange Forms Designer or other MAPI forms created using C++. The Items.Add method in the Outlook object model only works with Outlook forms.

To Create a Custom Form

If you already have a custom form stored in your Inbox and know the message class of the form, you can skip this section and go to the next section.

  1. In the Folder List, click the Inbox.
  2. On the Tools menu, point to Forms, and click Design a Form.
  3. Click Message, and then click Open.
  4. Click the (P.2) page of the form.
  5. If the Control Toolbox is not visible, on the Form menu, click Control Toolbox.
  6. Select a control from the Control Toolbox and drag it to the form.
  7. On the Tools menu, point to Forms, and then click Publish Form.
  8. In the Look in list, select Inbox.
  9. For the display name, type FormsTest, and then click Publish. Notice that the message class is IPM.Note.MyForm.
  10. Click Yes to select the Save Form Definition with Item check box.
  11. Close the form and do not to save it.

To Create the VBA Code

To create the code to open the form, follow these steps:

  1. On the Tools menu, point to Macro, and click Visual Basic Editor.

  2. In the Project - Project1 pane, double-click Project1, and double-click Microsoft Outlook Objects.

  3. Double-click ThisOutlookSession to open a code window.

  4. In the code window, enter the following code:

    Sub DisplayForm()
       Set myFolder = Session.GetDefaultFolder(olFolderInbox)
       Set myItem = myFolder.Items.Add("IPM.Note.MyForm")
       myItem.Display
    End Sub
    

    This code assumes that the name of your form is MyForm. Be sure to modify the third line of code if your form's message class is different.

  5. On the File menu, click Save Project1.

  6. Close the Visual Basic Editor.

To Create the Toolbar Button

  1. On the View menu, point to Toolbars, and click Customize.
  2. On the Commands tab in the Categories list, click Macros. The macro will be listed as Project1.ThisOutlookSession.DisplayForm.
  3. Drag the macro name to a toolbar.
  4. With the toolbar button selected, click Modify Selection, to make any desired changes to the appearance of the button.
  5. Click Close.

To Modify the Code

This code can be used with any mail message form, regardless of whether it is published in the Personal Forms Library, Organizational Forms Library, or the Inbox folder. However, other types of forms may be published in a specific folder and the resultant items are saved to that folder. This would typically be the case if you create a custom contact form, for example.

You may need to alter the code so that the custom form can be found in a specific folder (the folder where it was published) and so the item is saved in the correct folder. The following line of code from the sample above handles this:

Set myFolder = Session.GetDefaultFolder(olFolderInbox)

This line of code assumes that you want to use the default Inbox folder. If you want to use a different folder, substitute one of the following Outlook constants for olFolderInbox:

  • olFolderDeletedItems
  • olFolderOutBox
  • olFolderSentMail
  • olFolderCalendar
  • olFolderContacts
  • olFolderJournal
  • olFolderNotes
  • olFolderTasks

The line of code also assumes that the folder you want to use is one of the default set of folders. The default set of folders are those folders that are at the same level as the Inbox which receives incoming mail. However, if you want to use a custom form that is published in another folder, you must modify the code appropriately.

For more information on how to reference other folders in Outlook, see the Referencing Existing Folders section of the Programming Examples for Referencing Items and Folders tip in this article.

Examples of Opening Other Forms

To open a default contact item, change the code to:

Sub DisplayForm()
   Set myFolder = Session.GetDefaultFolder(olContactFolder)
   Set myItem = myFolder.Items.Add("IPM.Contact")
   myItem.Display
End Sub

To open a custom form with a message class of IPM.Note.Test that is published in the Test folder located in the default Inbox folder, change the code to:

Sub DisplayForm()
   Set myFolder = _
      Session.GetDefaultFolder(olFolderInbox).Folders("Test")
   Set myItem = myFolder.Items.Add("IPM.Note.Test")
   myItem.Display
End Sub

To open a custom form with a message class IPM.Appointment.Test that is published in the Personal Forms Library, or the Organizational Forms Library, change the code to:

Sub DisplayForm()
   Set myFolder = Session.GetDefaultFolder(olFolderCalendar)
   Set myItem = myFolder.Items.Add("IPM.Appointment.Test")
   myItem.Display
End Sub

To open a custom form in a Microsoft Exchange public folder titled My Public Folder, located at the top of the public folder hierarchy, use the following code:

Sub DisplayForm()
   Set myFolder1 = Session.Folders("Public Folders")
   Set myFolder2 = myFolder1.Folders("All Public Folders")
   Set myFolder3 = myFolder2.Folders("My Public Folder")
   Set myItem = myFolder3.Items.Add("IPM.Appointment.Test")
   myItem.Display
End Sub

To Open the Choose Forms Dialog Box

Instead of creating VBA code to open a form, you may prefer to open the Choose Forms dialog box from a toolbar button. To do this without programming, follow these steps:

  1. On the View menu, point to Toolbars, and click Customize.
  2. On the Commands tab under Categories, click File.
  3. In the list of Commands, drag Choose Form to a toolbar.
  4. Click Close.

Create a Custom Rule Using VBA

If the Outlook Rules Wizard does not provide a feature that meets your mail-routing needs, you can use Outlook VBA to create a custom rule. This tip describes how to get started setting up a simple rule and discusses some important considerations to keep in mind when creating a rule using VBA.

The following steps create a rule that automatically forwards any mail you receive outside of regular business hours to another e-mail address, such as the e-mail address you use at home, or to someone else who works the shift after yours.

  1. On the Tools menu, point to Macro, and click Visual Basic Editor.

  2. In the Project - Project1 pane, double-click Project1, and double-click Microsoft Outlook Objects.

  3. Double-click ThisOutlookSession to open a code window.

  4. In the code window, type the following code. Modify the line that specifies the e-mail address; substitute the e-mail address you want e-mail forwarded to:

    Public WithEvents myOlItems As Outlook.Items
    
    Public Sub Application_Startup()
       ' Reference the items in the Inbox. Because myOlItems is declared
       ' "WithEvents" the ItemAdd event will fire below.
       Set myOlItems = _
          Outlook.Session.GetDefaultFolder(olFolderInbox).Items
    End Sub
    
    Private Sub myOlItems_ItemAdd(ByVal Item As Object)
       ' If it's currently not between 9:00 A.M. and 5:00 P.M.
       If Time() < #9:00:00 AM# Or Time() > #5:00:00 PM# Then
    
          ' Check to make sure it is an Outlook mail message, otherwise
          ' subsequent code will probably fail depending on what type
          ' of item it is.
          If TypeName(Item) = "MailItem" Then
    
             ' Forward the item just received
             Set myForward = Item.Forward
    
             ' Address the message
             myForward.Recipients.Add "myaddress@mydomain.com"
    
             ' Send it
             myForward.Send
          End If
       End If
    End Sub
    
  5. On the File menu, click Save VBAProject.otm.

  6. Close the Visual Basic Editor.

  7. Restart Outlook so that the code will run.

For more information about how to make sure your code properly handles various types of items in Outlook, see the article OL2002: How To Handle Unexpected Items in a Collection in the Microsoft Knowledge Base.

The following considerations should be taken into account if you are considering implementing a rules solution using VBA:

  • Outlook must be running in order for the code to run. This is the same effect as using client-side rules in the Rules Wizard. If Outlook is not running at the time the message arrives, the rule will not work.
  • Your custom rule may conflict with other rules you have set up using the Rules Wizard. For example, if you are using Microsoft Exchange Server and create a server-side rule that moves mail from a specific individual to a specific folder, the mail is moved on the server and never reaches the Inbox. Therefore, the ItemAdd event does not run since an item is not added to the Inbox.
  • The code runs regardless of how an item is added to the Inbox. For example, if you accidently drag a message to your Inbox, the message is forwarded to the other e-mail account.
  • Outlook also has a NewMail event, but that event only runs when you get a new mail notification. If you receive three messages at once, the event only runs once. You can use the NewMail event to make sure that your VBA code only runs when you receive new messages, but you must add additional logic to the code to search for those messages that haven't been read before. So unfortunately both events tend to have an unwanted side effect:
    • The ItemAdd event makes it easy to act on all of the incoming items, but it also acts on those items you move to the Inbox yourself.
    • The NewMail event does not run when you drag items to the Inbox, but it is more difficult to program a solution to take into account that there are multiple items in the Inbox that your code must act on.

Working Successfully with Collections

The tips contained in this section will assist you in working with Outlook collections.

Properly Reference Members of a Collection

If you use Visual Basic, VBA, or VBScript to loop through items in a folder, you may see the modifications to those items are not saved. You may be unintentionally retrieving the item again from the Items collection, and any changes that you have made to an item are unexpectedly lost.

Many Outlook solutions modify the contents of items in a folder. In most scenarios you loop through the Items collection in the Outlook object model. If you do not properly reference the items in the collection, you may receive unexpected results.

Before modifying an item and saving it, you should set an object variable to the item, make changes to the item using the object variable, and then save the object.

**Note   **Be sure to reference the Microsoft Outlook 10.0 Object Library before running these code examples and be aware running this code will modify any existing contacts you have in your Contacts folder.

Consider the following VBA code sample that is designed to reset the birthday field for each contact in the default Contacts folder:

Sub ResetBirthdays1()
   Dim olns as Outlook.Namespace
   Dim oConItems As Outlook.Items
   Dim iNumItems As Integer
   Set ol = New Outlook.Application
   Set olns = ol.GetNamespace("MAPI")
   Set oConItems = olns.GetDefaultFolder(olFolderContacts).Items
   iNumItems = oConItems.Count
   For I = 1 to iNumItems
      oConItems.Item(I).Birthday = "1/1/4501"
      oConItems.Item(I).Close olSave
   Next
   Set oConItems = Nothing
   Set olns = Nothing
   Set ol = Nothing
End Sub

In the previous example, the loop is adequately structured and will process all of the items in the folder. However, within the loop, each time ConItems.Item(I) is executed, it retrieves the specific item from the collection of items. In this case, the Birthday is set for an item, but then the next line of code gets the item from the collection again. The end result is that an unmodified item is saved.

The following example is one way of modifying the previous code sample so that it executes correctly:

Sub ResetBirthdays2()
   Dim olns As Outlook.Namespace
   Dim oConItems As Outlook.Items
   Dim iNumItems As Integer
   Set ol = New Outlook.Application
   Set olns = ol.GetNamespace("MAPI")
   Set oConItems = olns.GetDefaultFolder(olFolderContacts).Items
   iNumItems = oConItems.Count
   For I = 1 to iNumItems
      Set oCurItem = oConItems.Item(I)
      oCurItem.Birthday = "1/1/4501"
      oCurItem.Close olSave
   Next
   Set oConItems = Nothing
   Set olns = Nothing
   Set ol = Nothing
End Sub

In this sample, oCurItem is set to a specific item in the collection, modifications to the item are made using that object variable, and the object is saved. This avoids getting an item from the collection and losing any changes.

The following example provides the same functionality as the previous example, but uses the For Each...Next structure to loop through the items:

Sub ResetBirthdays3()
   Dim olns as Outlook.Namespace
   Dim oConItems As Outlook.Items
   Set ol = New Outlook.Application
   Set olns = ol.GetNamespace("MAPI")
   Set oConItems = olns.GetDefaultFolder(olFolderContacts).Items
   For Each oCurItem in oConItems
      oCurItem.Birthday = "1/1/4501"
      oCurItem.Close olSave
   Next
   Set oConItems = Nothing
   Set olns = Nothing
   Set ol = Nothing
End Sub

Delete Items in a Collection

This tip describes how to use the Outlook object model to delete items in a collection. If you want to programmatically delete all of the members of a collection, there are a few approaches that will work but there are also a number of approaches that will not work. Unexpected results occur because a collection is changing as you delete members in it and the collection is not updated dynamically. Typically you will find that every other item in the collection is deleted.

The following VBA code example exhibits this behavior. Before running this code, create a subfolder of your Inbox called Test and copy (not move) some items into the folder so that they can be deleted.

Sub DeleteItems()
   Set ol = New Outlook.Application
   Set olns = ol.GetNamespace("MAPI")
   Set TestFolder = _
      olns.GetDefaultFolder(olFolderInbox).Folders("Test")
   Set TestItems = TestFolder.Items
   For Each Itm In TestItems
      Itm.Delete
   Next
End Sub

To delete all items in a collection, delete the items from the collection in reverse order using the following approach:

Sub DeleteItems()
   Set ol = New Outlook.Application
   Set olns = ol.GetNamespace("MAPI")
   Set TestFolder = _
      olns.GetDefaultFolder(olFolderInbox).Folders("test")
   Set TestItems = TestFolder.Items
   NumItems = TestItems.Count
   For I = NumItems To 1 Step -1
      TestItems(I).Delete
   Next
End Sub

If you need to delete a single item from a collection and want to make sure the collection is properly indexed, you may need to retrieve the collection of items again. In the example above, the following line of code retrieves the items from the folder again:

Set TestItems = TestFolder.Items

Handle Unexpected Items in a Collection

If you are using the Outlook object model to loop through items in a folder, you should make sure your solution will work even if the folder contains items that you might not expect to be there.

Some of the items that you might unexpectedly find in a folder include:

  • A Meeting or Task Request item in the Inbox.
  • An item that is a file from an external source, such as a Word document or an Excel spreadsheet. These files may be directly posted into a folder from another application, or they may have been dragged into a folder.
  • A Conflict message sent by Microsoft Exchange, if more than one person has edited an item at the same time in a public folder.
  • An item that is based on a form designed using the Exchange Forms Designer (EFD). These types of items do not function exactly like Outlook items in all circumstances. For example, you cannot programmatically add an attachment that is a link to an EFD-based item.
  • A Distribution List item in a Contacts folder. These lists are stored in the default Contacts folder and have a message class of IPM.DistList.

The Inbox typically poses a concern since the user generally has less control over what items are placed in that folder. Also, Outlook fully introduces Distribution Lists into the Contacts folder.

Typically, you will not run into problems when your code references one of these items. Problems usually occur when you try to reference a property of a particular item type and that property does not exist.

The following are approaches you can use to avoid these types of problems. Choose the approach that is best suited to your solution, the type of folder you are working with, and the types of items that could potentially affect your solution.

  • Use the TypeName function to test the type of object being referenced.

    If TypeName(objMyItem) = "ContactItem" Then...
    
  • Check the MessageClass property of an item.

    If Left(objMyItem.MessageClass, 11) = "IPM.Contact" Then...
    
  • Use error trapping to simply skip over lines of code that may potentially cause a problem.

    For Each oMyMailItem in oMyInboxItems
       On Error Resume Next
       oMyMailItem.VotingOptions = ""
       oMyMailItem.Save
    Next
    

Programming Examples for Referencing Items and Folders

The Outlook object model is commonly used to access various types of items in folders. This tip provides an overview of the various methods, properties, and objects that can be used to refer to Outlook items and folders. Specifically, the following topics are summarized:

Referencing Existing Folders

  • GetDefaultFolder Method
  • Folders Object
  • Parent Property
  • GetSharedDefaultFolder Method
  • GetFolderFromID Method

Creating and Referencing New Folders

  • Folders.Add Method

Creating and Referencing New Items

  • CreateItem Method
  • Items.Add Method
  • CreateItemFromTemplate Method

Referencing Existing Items

  • Using Items(I) or For Each...Next
  • Using Items("This is the subject")
  • Find Method
  • Restrict Method

**Note   **VBScript code must use the numeric value of the constants that are defined in the Outlook object library. For additional information, see the article OL2002: List of Outlook Object Model Constants in the Microsoft Knowledge Base.

Referencing Existing Folders

GetDefaultFolder Method:

Default folders are those that are at the same level as the Inbox that receives incoming mail. If you have more than one Inbox in your profile, pressing CTRL+SHIFT+I selects the default Inbox. The default folders are those that most users work with regularly, such as the Calendar, Contacts, and Tasks folders. You can easily refer to these folders using the GetDefaultFolder method. GetDefaultFolder takes one argument, which is the type of folder you want to refer to. The following examples assign the object variable MyFolder to the default Contacts folder:

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
Set MyFolder = olns.GetDefaultFolder(olFolderContacts)
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
Set MyFolder = olns.GetDefaultFolder(10)
...

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 any other folder that is not a default Outlook folder.

The following examples illustrate how to refer to a public folder called My Public Folder. Note that you typically start at the top-most folder and work your way down to the folder you need to reference. Also note that the folder names are case-sensitive and must exactly match the names as they appear in the Outlook folder list.

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
Set MyFolder1 = olns.Folders("Public Folders")
Set MyFolder2 = MyFolder1.Folders("All Public Folders")
Set MyFolder3 = MyFolder2.Folders("My Public Folder")
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
Set MyFolder1 = olns.Folders("Public Folders")
Set MyFolder2 = MyFolder1.Folders("All Public Folders")
Set MyFolder3 = MyFolder2.Folders("My Public Folder")
...

The following examples illustrate how you can refer to a folder called Business Tasks, which is a subfolder of the default Tasks folder.

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
Set MyTasksFolder = olns.GetDefaultFolder(olFolderTasks)
Set MyFolder = MyTasksFolder.Folders("Business Tasks")
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
Set MyTasksFolder = olns.GetDefaultFolder(13)
Set MyFolder = MyTasksFolder.Folders("Business Tasks")
...

Parent Property

If you already have a reference to an Outlook item or folder, then you can use its Parent property to create a reference to the folder the item or folder is located in.

The following examples return the name of a folder for a particular item:

...
' VBA code example.
Set ol = New Outlook.Application
' Create new item.
Set MyItem = ol.CreateItem(olMailItem) 
' Save it to Drafts.
MyItem.Save                            
' MyFolder = Drafts.
Set MyFolder = MyItem.Parent           
...
...
' VBScript code example.
' Returns the folder of the current item.
Set MyFolder = Item.Parent
...

GetSharedDefaultFolder

You can use this method if someone has given you delegate permissions to one of their default folders. For additional information about accessing other people's folders, see the article OL2002: How to Open Someone Else's Calendar or Other Folder in the Microsoft Knowledge Base.

The GetSharedDefaultFolder method is used in the same fashion as GetDefaultFolder, except you specify one additional argument—the name of the other person's folder you want to reference. This example first resolves the other person's name to verify that it is a valid name that can be used with the GetSharedDefaultFolder method.

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
Set myRecipient = olns.CreateRecipient("John Smith")
myRecipient.Resolve
If myRecipient.Resolved Then
   Set JohnFolder=olns.GetSharedDefaultFolder _
      (myRecipient, olFolderContacts)
End If
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
Set myRecipient = olns.CreateRecipient("John Smith")
myRecipient.Resolve
If myRecipient.Resolved Then
   Set JohnFolder = olns.GetSharedDefaultFolder(myRecipient, 10)
End If
...

GetFolderFromID

This method would typically be used only in more complex solutions where a solution keeps track of both the StoreID and EntryID of a folder so that it can be quickly referenced at a later time.

For additional information about using the GetFolderFromID method, see the article OL2002: Programming with EntryIDs and StoreIDs in the Microsoft Knowledge Base.

Creating and Referencing New Folders

Folders.Add Method

Using the Add method on the Folders collection allows you to create a new folder. The first argument specifies the name of the folder and the second argument specifies the type of folder. The following example adds a Business Tasks subfolder in your default Tasks folder. Because the folder type is not specified, it will inherit the type of the parent folder.

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
Set MyTasksFolder = olns.GetDefaultFolder(olFolderTasks)
Set MyNewFolder = MyTasksFolder.Folders.Add("Business Tasks")
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
Set MyTasksFolder = olns.GetDefaultFolder(13)
Set MyNewFolder = MyTasksFolder.Folders.Add("Business Tasks")
...

Creating and Referencing New Items

CreateItem Method

The CreateItem method creates a new default Outlook item. If you need to create an item based on a custom form you have created, use the Items.Add method below. The CreateItem method is conveniently located off of the top-level application object in the Outlook object model. The method takes only one argument, a constant indicating the type of item to create.

...
' VBA code example.
Set ol = New Outlook.Application
Set MyTaskItem = ol.CreateItem(olTaskItem)
MyTaskItem.Display
...
...
' VBScript code example.
Set MyTasktem = Item.Application.CreateItem(3)
MyTaskItem.Display
...

Items.Add Method

Using the Add method on the Items collection allows you to create a new item based on any message class, whether it is a default Outlook message class such as IPM.Contact, or a message class for a custom form, such as IPM.Contact.MyForm. In order to use the Items.Add method, you must first reference the folder where you want to create a new item.

For additional information about message classes, click the article OL2002: How to Update Existing Items to Use a New Custom Form in the Microsoft Knowledge Base.

The following examples use the Items.Add method to create a new item based on a custom contact form called MyForm:

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
Set myFolder = olns.GetDefaultFolder(olFolderContacts)
Set MyItem = MyFolder.Items.Add("IPM.Contact.MyForm")
MyItem.Display
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
Set myFolder = olns.GetDefaultFolder(10)
Set MyItem = MyFolder.Items.Add("IPM.Contact.MyForm")
MyItem.Display
...

The following examples use the Items.Add method to create a new default contact item:

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
Set myFolder = olns.GetDefaultFolder(olFolderContacts)
Set MyItem = MyFolder.Items.Add
MyItem.Display
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
Set myFolder = olns.GetDefaultFolder(10)
Set MyItem = MyFolder.Items.Add
MyItem.Display
...

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

CreateItemFromTemplate Method

Use the CreateItemFromTemplate method to create a new item based on an Outlook template file (.oft) or .msg file format. Because most forms are published in a folder or forms library, this method is not commonly used. Probably the most common reason to use this method would be if you were creating a Microsoft Visual Basic Setup program to install forms for an Outlook solution. This would typically be done for users who do not have network access or typically work offline in Outlook. The Visual Basic program would do the following:

  1. Start Outlook.
  2. Use CreateItemFromTemplate to open a form from a network share or disk.
  3. Using the Outlook object model, publish the form for later use.
...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
' Set MyFolder to the default contacts folder.
Set MyFolder = olns.GetDefaultFolder(olFolderContacts)
' Set MyItem to an .oft file on a floppy disk.
Set MyItem = ol.CreateItemFromTemplate("A:\Contact.oft")
' Set MyForm to the item Form Description for publishing.
Set MyForm = MyItem.FormDescription
' Name the form, which also sets its message class.
MyForm.Name = "My Contact"
' Publish the folder to the Contacts folder.
MyForm.PublishForm olFolderRegistry, MyFolder
' Close and do not save changes to the item.
MyItem.Close olDiscard
...

Referencing Existing Items

Using Items(I) or For Each...Next

Typically, these approaches are used to loop through all of the items in a folder. The Items collection contains all of 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 I = 1 to n programming construct.

You can use the For Each...Next programming construct to loop through the items in the collection without specifying an index. Both approaches achieve the same result.

The following examples use the Items(I) approach to loop through all of the contacts in the Contacts folder and display their FullName field in a dialog box.

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
' Set MyFolder to the default contacts folder.
Set MyFolder = olns.GetDefaultFolder(olFolderContacts)
' Get the number of items in the folder.
NumItems = MyFolder.Items.Count
' Set MyItem to the collection of items in the folder.
Set MyItems = MyFolder.Items
' Loop through all of the items in the folder.
For I = 1 to NumItems
   MsgBox MyItems(I).FullName
Next
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
' Set MyFolder to the default contacts folder.
Set MyFolder = olns.GetDefaultFolder(10)
' Get the number of items in the folder.
NumItems = MyFolder.Items.Count
' Set MyItem to the collection of items in the folder.
Set MyItems = MyFolder.Items
' Loop through all of the items in the folder.
For I = 1 to NumItems
   MsgBox MyItems(I).FullName
Next
...

The following examples use the For Each...Next construct to achieve the same result as the preceding examples:

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
' Set MyFolder to the default contacts folder.
Set MyFolder = olns.GetDefaultFolder(olFolderContacts)
' Set MyItems to the collection of items in the folder.
Set MyItems = MyFolder.Items
For Each SpecificItem in MyItems
   MsgBox SpecificItem.FullName
Next
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
' Set MyFolder to the default contacts folder.
Set MyFolder = olns.GetDefaultFolder(10)
' Set MyItem to the collection of items in the folder.
Set MyItems = MyFolder.Items
For Each SpecificItem in MyItems
   MsgBox SpecificItem.FullName
Next
...

Using Items("This is the subject")

You can also use the Items collection and specify a text string that matches the Subject field of an item. This approach is not commonly used.

The following examples display an item in the Inbox whose subject contains Please help on Friday!

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
' Set MyFolder to the default Inbox.
Set MyFolder = olns.GetDefaultFolder(olFolderInbox)
Set MyItem = MyFolder.Items("Please help on Friday!")
MyItem.Display
...
...
' VBScript code example.
Set olns = Item.Application.GetNameSpace("MAPI")
' Set MyFolder to the default Inbox.
Set MyFolder = olns.GetDefaultFolder(6)
Set MyItem = MyFolder.Items("Please help on Friday!")
MyItem.Display
...

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 check for additional items that meet the same search criteria.

The following examples search to see if you have any high priority appointments.

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNamespace("MAPI")
Set myFolder = olns.GetDefaultFolder(olFolderTasks)
Set MyTasks = myFolder.Items
' Importance corresponds to Priority on the task form.
Set MyTask = MyTasks.Find("[Importance] = ""High""")
If MyTask Is Nothing Then ' the Find failed
   MsgBox "Nothing important. Go party!"
Else
   MsgBox "You have something important to do!"
End If
...
...
' VBScript code example.
Set olns = Item.Application.GetNamespace("MAPI")
Set myFolder = olns.GetDefaultFolder(13)
Set MyTasks = myFolder.Items
' Importance corresponds to Priority on the task form.
Set MyTask = MyTasks.Find("[Importance] = ""High""")
If MyTask Is Nothing Then ' the Find failed
   MsgBox "Nothing important. Go party!"
Else
   MsgBox "You have something important to do!"
End If
...

Restrict Method

The Restrict method is similar to the Find method, but instead of returning a single item, it returns a collection of items that meet the search criteria. For example, you might use this method to find all contacts who work at the same company.

The following examples display all of the contacts who work at ACME Software:

...
' VBA code example.
Set ol = New Outlook.Application
Set olns = ol.GetNameSpace("MAPI")
Set MyFolder = olns.GetDefaultFolder(olFolderContacts)
Set MyItems = MyFolder.Items
MyClause = "[CompanyName] = ""ACME Software"""
Set MyACMEItems = MyItems.Restrict(MyClause)
For Each MyItem in MyACMEItems
   MyItem.Display
Next
...
...
' VBScript code example.
' Requires VBScript version 2.0 or later.
Set olns = Item.Application.GetNameSpace("MAPI")
Set MyFolder = olns.GetDefaultFolder(10)
Set MyItems = MyFolder.Items
MyClause = "[CompanyName] = ""ACME Software"""
Set MyACMEItems = MyItems.Restrict(MyClause)
For Each MyItem in MyACMEItems
   MyItem.Display
Next
...