“下标超出范围” - 中断模式正常

时间:2017-04-07 22:18:20

标签: vba outlook outlook-vba outlook-2013

就像标题所说的那样,我的代码中有一个超出范围错误的下标...但奇怪的是,当我进入break模式调试时,错误永远不会触发。

要进行故障排除,我在代码中添加了一个断点,直到收到错误。然后我逐行将断点向上移动,直到找到“破坏”允许代码执行的位置。在这些情况下,代码执行到较低的函数,接收另一个错误(它应该是,我仍在调试。

这似乎是令人讨厌的代码块。当我在循环结束时断开并按住F5时,它会完全执行。如果在代码中没有中断模式或断点,则会抛出下标错误。

'get all items in desired inbox, add all items to collection
Set supportBox = owaNamespace.Folders("FOLDER NAME REMOVED").Folders("Inbox")
Set allMailItems = supportBox.Items

'create array of MailItems to hold desired emails
Dim validItems() As Outlook.mailItem

'iterate through all items to look for valid notices
For Each oItem In allMailItems

    'function takes an item, confirms if MailItem from desired sender
    If IsValidNoticeEmail(oItem, MAIL_ITEM, SENDER_EMAIL) Then

        'convert object to MailItem before adding to array
        Dim newMail As Outlook.mailItem
        Set newMail = oItem

        'Get current array upper index
        Dim oldLength As Integer
        oldLength = UBound(validItems)

        'expand array by one at upper bound and add mail item at that location
        ReDim Preserve validItems(oldLength + 1)
        Set validItems(oldLength + 1) = newMail

    End If
Next oItem

所以不确定这是否是用户错误(5年以后返回VBA),或者是否存在时间问题,其中中断为初始化步骤提供了足够的时间,在没有运行代码的情况下无法按时完成符。

1 个答案:

答案 0 :(得分:1)

你可以采取相反的行动:

  • 首先,将数组调整为可能的有效邮件的最大数量

  • 然后,一旦你的循环结束,将其大小调整为找到的有效邮件的实际数量

如下:

'get all items in desired inbox, add all items to collection
Set supportBox = owaNamespace.Folders("FOLDER NAME REMOVED").Folders("Inbox")
Set allMailItems = supportBox.Items
if allMailItems.Count = 0 Then Exit Sub

'create array of MailItems to hold desired emails
Dim oldLength As Integer
Dim newMail As Outlook.mailItem
ReDim validItems(1 to allMailItems.Count) As Outlook.mailItem

'iterate through all items to look for valid notices
For Each oItem In allMailItems

    'function takes an item, confirms if MailItem from desired sender
    If IsValidNoticeEmail(oItem, MAIL_ITEM, SENDER_EMAIL) Then

       'convert object to MailItem before adding to array
        Set newMail = oItem

        'Update current array upper index
        oldLength = oldLength + 1

        Set validItems(oldLength) = newMail

    End If
Next oItem
'Resize array to actual number of valid mail items or erase it if no valid mail items found
If oldLength >0 Then
    ReDim Preserve validItems(1 to oldLength)
Else
    Erase validItems
End If