运行时错误91,未设置对象,试图自动下载电子邮件附件

时间:2019-05-07 13:22:25

标签: vba outlook-vba

我正在尝试自动下载Outlook上的电子邮件附件。我收到运行时错误,并且不确定如何解决。我可能只是缺少一些基本知识。我一直在盯着这个看很久。

我尝试在Sub SaveAttachments的括号中将MItem作为Outlook.MailItem放置,但​​这导致程序无法加载。

Sub SaveAttachments()
    Dim oAttachment As Outlook.Attachment
    Dim MItem As Outlook.MailItem
    Dim sSaveFolder As String
    sSaveFolder = "C:\Users\______\Desktop\Test Folder"
    For Each oAttachment In MItem.Attachments
            oAttachment.SaveAsFile sSaveFolder & oAttachment.DisplayName
    Next
End Sub

当我尝试调试时,它会突出显示MItem.Attachments中的每个oAttachment

我故意插入____。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果我的评论不清楚:

Public Sub SaveAttachments(ByRef MItem As Outlook.MailItem)
  Dim oAttachment As Outlook.Attachment
  Dim sSaveFolder As String
  sSaveFolder = "C:\Users\______\Desktop\Test Folder\"
  For Each oAttachment In MItem.Attachments
    With oAttachment
      If LCase(Right$(.DisplayName, 4)) = ".csv" then
        .SaveAsFile sSaveFolder & .DisplayName
      End If
    End With
  Next
End Sub

注1:我在sSaveFolder的末尾添加了“ \”。

注2:SaveAsFile会覆盖任何具有相同名称的现有文件。仅当DisplayName始终是唯一的,或者如果您愿意重新使用DisplayName时丢失旧文件时,此代码才有效。

注3:即使未将签名和图像列为用户的附件,它们也保留为附件。您应该考虑检查扩展名,以确保仅保存所需的附件。

注意4:如果要在桌面上保存文件,请使用:

' Technique for locating desktop from answer by Kyle:
'                     http://stackoverflow.com/a/17551579/973283

Dim Path As String
Path = CreateObject("WScript.Shell").SpecialFolders("Desktop")