【发布时间】: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
【问题讨论】:
-
@niton,在那个问题中,OP 尝试使用
Worksheet对象来访问属性Attachments。这里我使用Outlook.MailItem对象的属性Attachments。