首页 > 解决方案 > 在我的驱动器中保存 Outlook 消息的问题

问题描述

我想在我的驱动器中保存 Outlook 消息,但出现运行时错误 287:“应用程序定义或对象错误”

Sub extract_outlook_emails()

Dim ap As Outlook.Application

Dim fl As Outlook.MAPIFolder

Dim it As Outlook.MailItem

Dim space As Outlook.Namespace

Dim i As Long

Dim p As Variant


Dim str As String


Set ap = New Outlook.Application

 

Set space = ap.GetNamespace("MAPI")

 

Set fl = space.GetDefaultFolder(olFolderInbox)

For Each it In fl.Items

If it.Class = olMail Then

    If VBA.InStr(1, it.Subject, "Product_19854") Then

   

p = SaveSelectMail(it.Subject)


        str = "\c:"&environ("user profile") & p & "-" & VBA.Format(it.ReceivedTime, "ddmmyyyy", vbUseSystemDayOfWeek) & ".msg"

 it.SaveAs str, OlSaveAsType.olMSG

      
    End If


 End If

Next it


end sub

标签: vbaoutlook

解决方案


首先,一个 Outlook 文件夹可能包含不同类型的项目 - 邮件、日历、任务、文档项目等。但在代码中,您正在遍历所有类型为 的项目MailItem

Dim it As Outlook.MailItem
...
For Each it In fl.Items

您需要定义itas 对象并使用后期绑定技术来避免代码中的错误。

遍历文件夹中的所有项目也不是一个好主意。要查找主题包含关键字(任何您的搜索条件)的所有邮件项目,您可以使用该类的Find/FindNextRestrict方法Items。在以下文章中阅读有关它们的更多信息:

但是如果您需要在多个文件夹中搜索项目,您可以考虑使用类的AdvancedSearch方法ApplicationAdvancedSearch在 Outlook 中使用该方法的主要好处是:

  • 搜索在另一个线程中执行。您不需要手动运行另一个线程,因为该AdvancedSearch方法会在后台自动运行它。
  • 可以在任何位置(即超出某个文件夹的范围)搜索任何项目类型:邮件、约会、日历、便笺等。和Restrict/方法可以应用于特定的集合(参见 Outlook 中类的Find属性)。FindNextItemsItemsFolder
  • 完全支持 DASL 查询(自定义属性也可用于搜索)。您可以在 MSDN中的过滤文章中阅读有关此内容的更多信息。为了提高搜索性能,如果为商店启用了即时搜索,则可以使用即时搜索关键字(请参阅类的IsInstantSearchEnabled属性Store)。
  • Stop您可以使用类的方法随时停止搜索过程Search

有关详细信息,请参阅以编程方式在 Outlook 中进行高级搜索:C#、VB.NET


推荐阅读