VBA Outlook数组索引超出范围

时间:2016-01-20 14:17:28

标签: arrays vba outlook indexoutofboundsexception

我有以下代码可自动删除超过两个月的电子邮件:

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

然而,错误:

Array index out of bounds

不断被召唤:

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

使用Debug.Print我已经查看了上面的代码行:oDeletedItems.Items.Count - 1,并且计数是1889,因此数组中有元素。

如果数组中有对象,为什么会出现此错误?

1 个答案:

答案 0 :(得分:2)

如果Items.Count,删除项目的行为会减少i并使其与当前值不同步。

向后循环,以便i始终是最后一项(保证存在):

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