首页 > 解决方案 > 如何自动保存附件并覆盖?

问题描述

我正在尝试从 Outlook 电子邮件中提取 Excel 报告,并将其保存在我的 Documents 文件夹中名为“OLAttachments”的文件夹中。

我还需要它来覆盖前一天的文件。这些电子邮件附件每天都具有相同的名称。

这就是我到目前为止所拥有的。每次电子邮件通过时,它都会保存一个新文件,而我想覆盖现有文件。

Public Sub SaveAttachmentsToDisk(MItem As Outlook.MailItem)
Dim oAttachment As Outlook.Attachment
Dim sSaveFolder As String
sSaveFolder = "C:\Users\fmustapha\Documents\Outlook Attachments"
For Each oAttachment In MItem.Attachments
    oAttachment.SaveAsFile sSaveFolder & oAttachment.DisplayName
Next
End Sub

标签: vbaoutlook

解决方案


我在我的服务器上执行此操作,我每晚都会收到一封附有 Excel 文件的电子邮件,该电子邮件会自动转发到我的服务器,该 Outlook 代码会在其中保存附件。请注意,其中有一个子句来确保文件来自我并确保它是 Excel 文件:

Private WithEvents olItems As Outlook.Items

Private Sub Application_Startup()
Dim objNS As Outlook.NameSpace
Set objNS = GetNamespace("MAPI")
Set olItems = objNS.GetDefaultFolder(olFolderInbox).Items
Set objNS = Nothing
End Sub

Private Sub olItems_ItemAdd(ByVal Item As Object)
    Dim NewMail As Outlook.MailItem
    Dim Atts As Attachments
    Dim Att As Attachment
    Dim strPath As String
    Dim strName As String

    If Item.Class = olMail Then
       Set NewMail = Item
    End If
    strPath = "C:\Reporting Archive\Sales Files\"
    If NewMail.Sender = "Dan Donoghue" Then

       Set Atts = Item.Attachments

       If Atts.Count > 0 Then
          For Each Att In Atts
              If InStr(LCase(Att.FileName), ".xls") > 0 Then Att.SaveAsFile strPath & Att.FileName
          Next
       End If
    End If
End Sub

ThisOutlookSession一旦您将其关闭并重新打开Outlook,它就会进入VBE,它将起作用。

要保存在顶部,我建议您先删除现有文件(您可以kill为此使用命令,然后简单地保存新文件)。

你可以通过替换这个来做到这一点:

If InStr(LCase(Att.FileName), ".xls") > 0 Then Att.SaveAsFile strPath & Att.FileName

有了这个:

If InStr(LCase(Att.FileName), ".xls") > 0 Then
    Kill strPath & Att.FileName
    Att.SaveAsFile strPath & Att.FileName
End If

在我的代码中


推荐阅读