vba - 如何自动保存附件并覆盖?
问题描述
我正在尝试从 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
解决方案
我在我的服务器上执行此操作,我每晚都会收到一封附有 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
在我的代码中
推荐阅读
- mysql - MySQL #1452 - 无法添加或更新子行:外键约束失败 ON DELETE CASCADE ON UPDATE CASCADE)
- javascript - 如何从地图对象的值执行函数
- discord.js - 尝试从 youtube 视频流式传输音频时,DiscordJS v13 AudioPlayer 卡在缓冲上
- php - 如何根据用户输入检索数组?
- huawei-mobile-services - 在设置 DevEco 时,我无法设置 HarmonyOS SDK 路径,这是什么问题?
- r - r 将带有嵌入函数的 r 函数转换为 Rcpp
- html - 如何使用 Bootstrap 5 让 Div 部分浮动到另一个 Div 的底部(或中心)
- css - 在 ReactJS 中,如何在 JSX 中的 span 元素之间更改一条线?
- javascript - 如何格式化在胜利图中随数据和时间移动的折线图
- javascript - 带有 HTML/CSS 的登录页面