Sauron
Sauron

Reputation: 6657

VBA Outlook Array Index out of bounds

I have the following code to automatically delete emails that are older than two months:

Sub RemoveAutomaticItemsInDeletedItems()

    If MsgBox("Delete items from from Deleted Items folder ?", vbYesNo, "Confirm") = vbYes Then

        Dim oDeletedItems As Outlook.Folder
        Dim obj As Outlook.MailItem
        Dim i As Integer

        'Obtain a reference to deleted items folder
        Set oDeletedItems = Application.Session.GetDefaultFolder(olFolderDeletedItems)
        For i = 1 To oDeletedItems.Items.Count - 1
         If oDeletedItems.Items(i).Class = olMail Then
          Set obj = oDeletedItems.Items.Item(i)
           If obj.ReceivedTime <= DateAdd("m", -2, Now) Then

             'Deleting them
             Debug.Print obj.SenderEmailAddress
             'Debug.Print obj.Subject

              obj.Delete

          End If
         End If
        Next
        MsgBox "Items have been deleted"
    End If

End Sub

However, the error:

Array index out of bounds

is continually called on the line:

If oDeletedItems.Items(i).Class = olMail Then

using Debug.Print I have looked into the line of code just above that: oDeletedItems.Items.Count - 1, and the count is 1889 thus there are elements in the array.

Why would this error persist if there are objects within the array?

Upvotes: 1

Views: 1874

Answers (1)

Alex K.
Alex K.

Reputation: 175866

The act of deleting an item decrements Items.Count and takes it out of sync with the current value if i.

Loop backwards so that i is always the last item (which is guaranteed to exist):

For i = oDeletedItems.Items.Count - 1 To 1 Step -1

Upvotes: 2

Related Questions