OL98: How to Properly Loop Through Items in a Collection

ID: Q195699

The information in this article applies to:

SUMMARY

This article describes common scenarios and considerations to take into account when programming with collections. The following topics are covered:

NOTE: The first two topics apply to all types of collections, including Items, Attachments, and Recipients. The last topic only applies to Items.

MORE INFORMATION

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft Support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs. If you have limited programming experience, you may want to contact the Microsoft fee-based consulting line at (800) 936-5200. For more information about the support options available from Microsoft, please see the following page on the World Wide Web:

   http://www.microsoft.com/support/supportnet/refguide/default.asp

Properly Referencing Members of a Collection

If you use Visual Basic or Visual Basic for Applications code that loops through items in a folder, you may see the modifications to those items are not saved. You may be unintentionally re-retrieving the item 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.

Consider the following Visual Basic automation code sample, which is designed to reset the birthday field for each contact in the default Contacts folder:

NOTE: Be sure to reference the Outlook 98 Object Library before running these code examples and be aware running this code will modify any existing contacts you have in your 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 sample, 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 then following 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 as expected:

   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 the previous 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

Deleting All Members of 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 from within it and the collection is not updated dynamically. Typically you will find that every other item in the collection is deleted.

The following automation 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 workaround this problem, 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

Handling Unexpected Item Types

If you are looping 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. The Inbox typically poses the most concern since the user generally has less control over what items are placed in that folder.

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

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.

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.

REFERENCES

For more information about creating solutions with Microsoft Outlook 98, please see the following articles in the Microsoft Knowledge Base:

   Article-ID: Q180826
   Title     : OL98: Resources for Custom Forms and Programming

   Article-ID: Q182349
   Title     : OL98: Questions About Custom Forms and Outlook Solutions

Additional query words: OutSol OutSol98 vbscript
Keywords          : kbdta OffVBS 
Version           : WINDOWS:
Platform          : WINDOWS
Issue type        : kbprb

Last Reviewed: May 17, 1999