1

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?

1

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.