【问题标题】:How do you rename an attachment and save it in outlook?如何重命名附件并将其保存在 Outlook 中?
【发布时间】:2023-04-03 01:11:02
【问题描述】:

我想使用以下代码重命名 Outlook 中的附件。但我不知道该怎么做。

理想情况下,最好用发送者和当前日期重命名文件附件。因此,如果它是由 jill@gmail.com 发送的,它会将文件重命名为 jill@gmail.com230719

见下面的代码

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

    ' Get the path to your My Documents folder
    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    On Error Resume Next

    ' Instantiate an Outlook Application object.
    Set objOL = Application

    ' Get the collection of selected objects.
    Set objSelection = objOL.ActiveExplorer.Selection

' The attachment folder needs to exist
' You can change this to another folder name of your choice

    ' Set the Attachment folder.
    strFolderpath = strFolderpath & "\OLAttachments\"

    ' Check each selected item for attachments.
    For Each objMsg In objSelection

    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count

    If lngCount > 0 Then

    ' Use a count down loop for removing items
    ' from a collection. Otherwise, the loop counter gets
    ' confused and only every other item is removed.

    For i = lngCount To 1 Step -1

    ' Get the file name.
    strFile = objAttachments.Item(i).FileName

    ' Combine with the path to the Temp folder.
    strFile = strFolderpath & strFile

    ' Save the attachment as a file.
    objAttachments.Item(i).SaveAsFile strFile

    Next i
    End If

    Next

ExitSub:

Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

【问题讨论】:

    标签: vba outlook ms-office


    【解决方案1】:

    这一行是在代码中分配名称:

    strFile = objAttachments.Item(i).FileName
    

    改为:

    strFile = Split(objMsg.SenderEmailAddress, "@")(0) & Format(objMsg.ReceivedTime, "ddmmyyyy") & "." & Split(Right(objAttachments.Item(i).FileName,8), ".")(1)
    

    objMsg.SenderEmailAddress 会给你发件人的电子邮件地址

    objMsg.ReceivedTime会给你时间

    【讨论】:

    • 它按预期工作。唯一的小问题是它无法识别文件扩展名,因为如果保存它有 jill@gmail.com230719,它会将扩展名视为 .com230719。有没有办法只保存前五个字母然后保存日期?如 jill@230719
    • 使用更新后的答案 :)
    • 工作如梦。谢谢。我对 vba 编程相当陌生,所以对象和文件路径不熟悉
    • @don ...乐于助人。接受答案:)
    • 我现在才看到的最后一件事。可能有两个同名文件。如何避免该程序覆盖已保存的文件?同一天可以有两个文件具有相同的发件人(在本例中为 jill),但文件不同。我尝试了 strFile = strFolderpath & j & strFile ,其中 j 是一个变量,但它在搜索时失去了搜索 jill 发送的所有文件的有效性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多