【问题标题】:Outlook array index out of bounds when trying to display MailItem after MailItem.Attachments.Add has failed在 MailItem.Attachments.Add 失败后尝试显示 MailItem 时,Outlook 数组索引超出范围
【发布时间】:2025-12-17 06:40:01
【问题描述】:

我从 Excel VBA 宏调用 Outlook 以通过电子邮件发送附件。如果由于某种原因无法将附件添加到 MailItem,则在尝试显示 MailItem 时出现“数组索引超出范围”错误。

当我检查MailItem.Attachments.Count 的值时,它显示1,即使附件没有添加到电子邮件中。我尝试使用MailItem.Attachments.Remove 1 删除附件,但附件计数仍然显示1,并且尝试显示时仍然出现“数组索引越界”错误。

我遇到过this thread,它是关于用 C# 开发 Office 加载项的,它建议释放所有 COM 对象。我不知道该怎么做,甚至不知道它是否相关。我尝试将除MailItem 之外的所有对象设置为Nothing,但这没有帮助。

UPD:cmets 中提出的问题并没有解决我的问题。在那个问题中,错误的对象被用来访问Attachments 属性。这里我使用的是Outlook.MailItem.Attachments,我认为这是正确的。

示例代码如下:

Public Sub For*()
    Dim OutlookApp As Object
    Dim MailItem As Object
    Dim Attachments As Object
    Dim Attachment As Object
    
    Set OutlookApp = CreateObject("Outlook.Application")
    Set MailItem = OutlookApp.CreateItem(0)
    
    With MailItem
        .To = "test@test.com"
        .Subject = "test"
        .Body = "test"
        Set Attachments = .Attachments

        On Error Resume Next

        Set Attachment = Attachments.Add("C:\Temp\ThisFileDoesNotExist.txt") 
        If Err.Number = 0 Then
            On Error GoTo 0
            .Send                       '<-- This works fine because attachment was added successfully
        Else
            On Error GoTo 0
            'Attachment.Delete          'This and any of the below didn't work
            'Set Attachment = Nothing
            'Attachments.Remove 1
            'Set Attachments = Nothing
            
            .Display                    '<-- Error 440: Array index out of bounds on this line
        End If
    End With
        
End Sub

【问题讨论】:

标签: excel vba outlook


【解决方案1】:

使用On Error Resume Next,您发现有一个附件,您无法删除,这会触发“数组索引超出范围”错误。

测试文件而不是应用最后的代码On Error Resume Next

Option Explicit

Public Sub For*_FileExistsTest()

    Dim OutlookApp As Object
    Dim MailItem As Object
    Dim pathFile As String
    
    Set OutlookApp = CreateObject("Outlook.Application")
    Set MailItem = OutlookApp.CreateItem(0)
    
    With MailItem
    
        pathFile = "C:\Temp\ThisFileDoesNotExist.txt"
        
        If Len(dir(pathFile)) > 0 Then
        
            .Attachments.Add (pathFile)
            .Display
            
        Else
        
            MsgBox pathFile & " does not exist."
            .Display
            
        End If
        
    End With
    
End Sub

【讨论】:

  • 有道理,我想我会这样做。我更想知道一旦“添加”了附件,是否有办法修复 MailItem 对象,但我同意最好防止这种情况发生。感谢您的时间和回答。