NinjaWarrior
NinjaWarrior

Reputation: 25

Save Outlook attachment to a folder and Rename the file with date

I'm trying to save the daily system generated report attached to the e-mail to a folder.

Then, append the attachment filename with the date (modified date in the file). I am able to get the file saved to a folder. However, the renaming piece doesn't seem to work for me.

Can someone please help why the renaming piece isn't working? Much Thanks!

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

Upvotes: 1

Views: 1976

Answers (1)

0m3r
0m3r

Reputation: 12499

Your newName needs to be string NOT Object so Dim newName As String also I would assign objAtt.DisplayName to string variable

See Example

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

Upvotes: 1

Related Questions