Outlook VBA中如何为对象属性添加表格列?
问题描述
- 系统环境:Windows 11 Pro 64位、MS Office LTSC Pro Plus 2021
- 需求:构建记录所选电子邮件属性的电子表格,使用
oEmailFolder.GetTable(sFilter)生成Outlook表格,通过oOutlookTable.Columns.Add("property")添加所需属性列 - 核心问题:
Sender和Attachments属于对象类型,直接通过名称引用添加到表格列会报错:运行时错误 '-2147024809 (80070057)':属性"Attachments"不支持此操作 - 尝试的无效方案:
- 按照微软文档的Outlook命名空间格式尝试添加
Attachments:
报错:oColumns.Add ("urn:schemas-microsoft-com:office:outlook#Attachments")Run-time error '-2147024809 (80070057)': The property "urn:schemas-microsoft-com:office:outlook#Attachments" is unknown. - 尝试
urn:schemas:mailheader命名空间:
报错:oColumns.Add ("urn:schemas:mailheader#Attachments")Run-time error '-2147024809 (80070057)': The property "urn:schemas:mailheader#Attachments" does not support this operation.
- 按照微软文档的Outlook命名空间格式尝试添加
- 疑问:使用
oColumns.Add()方法引用此类对象属性的正确语法是什么?
解决方案
针对Attachments属性
Outlook的Table对象不支持直接添加Attachments集合类型的列,因为它不是单一值属性。要获取附件相关信息,需通过以下步骤处理:
- 遍历
Table的每一行,调用Row.GetItem()获取对应的邮件项 - 从邮件项的
Attachments集合中提取所需信息(如附件数量、文件名列表等) - 将提取的信息写入电子表格对应单元格
示例代码片段:
Dim oRow As Outlook.Row Dim oMail As Outlook.MailItem Dim attachmentCount As Integer Dim attachmentNames As String Dim rowNum As Integer rowNum = 2 ' 假设从工作表第2行开始写入 Do Until oTable.EndOfTable Set oRow = oTable.GetNextRow() Set oMail = oRow.GetItem() ' 获取附件数量 attachmentCount = oMail.Attachments.Count ' 拼接所有附件文件名 attachmentNames = "" For i = 1 To attachmentCount attachmentNames = attachmentNames & oMail.Attachments(i).FileName & ", " Next i If attachmentCount > 0 Then attachmentNames = Left(attachmentNames, Len(attachmentNames) - 2) ' 移除末尾多余的逗号和空格 End If ' 将信息写入工作表(ws为预先定义的工作表对象) ws.Cells(rowNum, "A").Value = attachmentCount ws.Cells(rowNum, "B").Value = attachmentNames rowNum = rowNum + 1 Loop
针对Sender属性
Sender是对象类型,无法直接添加到Table列,但可以添加对应的内置属性或命名空间属性来获取发送者信息:
- 获取发送者名称:使用内置属性名
"SenderName" - 获取发送者邮箱地址:使用内置属性名
"SenderEmailAddress",或命名空间格式"urn:schemas:httpmail#from"
示例代码:
' 添加发送者名称列 oColumns.Add ("SenderName") ' 添加发送者邮箱地址列 oColumns.Add ("SenderEmailAddress") ' 或使用命名空间格式添加邮箱地址列 oColumns.Add ("urn:schemas:httpmail#from")
内容的提问来源于stack exchange,提问作者NewSites
相关产品推荐
相关产品推荐

