将Outlook附件保存到文件夹并使用日期重命名该文件

时间:2017-04-14 23:26:25

标签: vba outlook outlook-vba

我正在尝试将附加到电子邮件的每日系统生成的报告保存到文件夹中。

然后,将附件文件名附加日期(文件中的修改日期)。我能够将文件保存到文件夹中。但是,重命名的部分似乎对我不起作用。

有人可以帮助为什么重命名的作品不起作用?非常感谢!

Public Sub saveAttachtoBIFolder(itm As Outlook.MailItem)
  Dim objAtt As Outlook.Attachment
  Dim saveFolder As String
  Dim fso As Object
  Dim oldName As Object

  Dim file As String
  Dim DateFormat As String
  Dim newName As Object


  saveFolder = "C:\BI Reports"


  Set fso = CreateObject("Scripting.FileSystemObject")
  On Error Resume Next

  For Each objAtt In itm.Attachments
      file = saveFolder & "\" & objAtt.DisplayName
      objAtt.SaveAsFile file
      Debug.Print "file="; file ' the full file path printed on immediate screen

      Set oldName = fso.GetFile(file) ' issue seems to start from here
      DateFormat = Format(oldName.DateLastModified, "yyyy-mm-dd ")
      newName = DateFormat & objAtt.DisplayName
      oldName.Name = newName

       Debug.Print "DateFormat="; DateFormat 'the date format printed on the immediate screen
      Set objAtt = Nothing
  Next

  Set fso = Nothing
 End Sub

1 个答案:

答案 0 :(得分:1)

您的 newName 需要string NOT Object ,所以Dim newName As String我也会分配objAtt.DisplayNamestring variable

参见示例

Set FSO = CreateObject("Scripting.FileSystemObject")
For Each objAtt In itm.Attachments
    File = saveFolder & "\" & objAtt.DisplayName
    objAtt.SaveAsFile File
    Debug.Print File ' the full file path printed on immediate screen

    Set oldName = FSO.GetFile(File) ' issue seems to start from here
    Debug.Print oldName

    Dim newName As String
    Dim AtmtName As String

    AtmtName = objAtt.DisplayName
    Debug.Print AtmtName


    DateFormat = Format(oldName.DateLastModified, "yyyy-mm-dd ")
    Debug.Print DateFormat

    newName = DateFormat & " " & AtmtName
    oldName.Name = newName
    Debug.Print newName 'the date format printed on the immediate screen
Next