How to save attachments and rename it - vba

I am having an issue getting my code to work. This is my first time running a VBA script. I have a large amount of emails coming in from a fax machine and I want to be able to download the attachments, rename the file to the subject line and then store them on my computer.
My first attempt, I tried to just write a macro so that I could manually do it but after doing some research, I was under the impression that I wanted to make rules work.
This is my first attempt at VBA so I'm not even sure I am running the macro or rule script correctly but I have a feeling I am just missing something in the code. Any thoughts?
Public Sub saveAttachtoDiskRule(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim fso As Object
Dim oldName
Dim file As String
Dim DateFormat As String
Dim newName As String
Dim enviro As String
enviro = CStr(Environ("USERPROFILE"))
saveFolder = enviro & "\" & "\destinationfolder\"
Set fso = CreateObject("Scripting.FileSystemObject")
For Each objAtt In itm.Attachments
file = saveFolder & objAtt.DisplayName
objAtt.SaveAsFile file
Set oldName = fso.GetFile(file)
newName = itm.Subject
oldName.Name = newName
Set objAtt = Nothing
Next
Set fso = Nothing
End Sub

Here is simple rule script
Public Sub saveAttachtoDisk(olItem As Outlook.MailItem)
Dim olAttachment As Outlook.Attachment
Dim SaveFolder As String
SaveFolder = "c:\temp\"
For Each olAttachment In olItem.Attachments
olAttachment.SaveAsFile SaveFolder & "\" & olAttachment.DisplayName
Set olAttachment = Nothing
Next
End Sub
Environ Function
The Environ function lets you get the Windows environment variables for the computer your code is currently running on, Like user name or the name of the temporary folder
Examples
user's profile folder example is
Environ("USERPROFILE") & "\Documents\Temp\"
result
Windows Vista/7/8: C:\Users\Omar\
Windows XP: C:\Documents and Settings\Omar\
"All Users" or "Common" profile folder
Environ("ALLUSERSPROFILE")
Temporary folder example is
Environ("TEMP") (or Environ("TMP") - is the same)
result: C:\Users\omar\AppData\Local\Temp

Related

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
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

VBA code update from Outlook 2016 to 2013

I wrote this code on an other PC which had Win10 and Office 2016. It is used in an outlook rule. It saves the xml files from the e-mail to a folder and change it to xlsx file in an other folder. In Outlook 2016 it runs properly. I copied it to an other notebook.
This notebook has Win10 and Office 2013 and this code run in Outlook 2013 without any error message but the xml files neither were saved into the given folder and nor were converted to xlsx.
What could be wrong in this code?
Option Explicit
Public Sub saveconvAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim dateFormat As String
Dim convFormat As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
saveFolder = "C:\Users\tulaj\Documents\xml\"
convFolder = "C:\Users\tulaj\Documents\xls\"
dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd HH-mm-ss")
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & dateFormat & objAtt.FileName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(saveFolder)
If UCase(Right(objAtt.FileName, Len(XML))) = UCase(XML) Then
NewFileName = convFolder & dateFormat & objAtt.FileName & "_conv.xlsx"
Set ConvertThis = Workbooks.Open(saveFolder & dateFormat & objAtt.FileName)
ConvertThis.SaveAs FileName:=NewFileName, FileFormat:= _
xlOpenXMLWorkbook
ConvertThis.Close
End If
Next
Set objAtt = Nothing
End Sub
In Tools-References are selected the falowings:
Visual Basic For Aplications
Microsoft Outlook 15.0 Object Library
OLE Automation
Microsoft Office 15.0 Object Library
Microsoft Excel 15.0 Object Library
Microsoft Scripting Runtime
This should work for you...
Option Explicit
Public Sub saveconvAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim SaveFolder As String
Dim convFolder As String
Dim DateFormat As String
Dim ConvFormat As String
Dim NewFileName As String
Dim ConvertThis As Object
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
SaveFolder = "C:\Temp\xml\"
convFolder = "C:\Temp\xls\"
DateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd HH-mm-ss ")
For Each objAtt In itm.Attachments
Debug.Print objAtt.FileName
objAtt.SaveAsFile SaveFolder & DateFormat & objAtt.FileName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(SaveFolder)
If UCase(Right$(objAtt.FileName, Len("XML"))) = UCase("XML") Then
NewFileName = convFolder & DateFormat & objAtt.FileName & "_conv.xlsx"
Set ConvertThis = Workbooks.Open(SaveFolder & DateFormat & objAtt.FileName)
ConvertThis.SaveAs FileName:=NewFileName, FileFormat:= _
xlOpenXMLWorkbook
ConvertThis.Close
End If
Next
Set objAtt = Nothing
End Sub
To Test it, select the Email and run the following code
Public Sub Test_Rule()
Dim Item As MailItem
Set Item = ActiveExplorer.Selection.Item(1)
saveconvAttachtoDisk Item
Set Item = Nothing
End Sub

Downloading and then extracting zipped attachments using an Outlook rule

I have a fairly straight forward scenario where I get an email every day with a zip file attached and I would like to be able to more easily parse this information. In order to do so I just need to be able to download the attachment to a folder and then extract it.
To download the attachment I did the following
Public Sub SaveZip(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "c:\temp\"
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
Set objAtt = Nothing
Next
End Sub
This works as expected, the .zip file gets dumped into the temp directory. I found the following code which on all accounts seems to be what I need to implement in order to extract the .zip
Set oApp = CreateObject("Shell.Application")
oApp.NameSpace(saveFolder).CopyHere oApp.NameSpace.Items
I have not been able to implement this into my existing code without generating a host of errors (due to my own lack of understanding I am sure)
Any input on this would be greatly appreciated
Final Edit
Got it, thanks to Tim for all the help. The following will download attachments (always named the same thing) from an incoming email into c:\temp, extract them to c:\temp\unzipped, rename the file, and finally delete the .zip in c:\temp.
Public Sub SaveZip(itm As Outlook.MailItem)
Const saveFolder = "C:\Temp\"
Const fileFolder = "C:\CBH\"
Dim objAtt As Outlook.Attachment
Dim oApp As Object
Dim dName As Variant
For Each objAtt In itm.Attachments
dName = objAtt.DisplayName
objAtt.SaveAsFile saveFolder & dName
Set oApp = CreateObject("Shell.Application")
oApp.NameSpace("C:\CBH").CopyHere _
oApp.NameSpace(saveFolder & dName).Items
Name fileFolder & "CallsByHour.xls" As fileFolder & "CBH-" & Format(Date, "yyyymmdd") & ".xls"
Kill saveFolder & dName
Next
End Sub
Assuming you're coding in Outlook, this will process the item selected in Outlook, saving the attachment to C:\Temp and extracting the zip contents to C:\Temp\unzipped
EDIT (untested) - added date-time based subfolder
Sub Tester()
SaveZip Application.ActiveExplorer.Selection.Item(1)
End Sub
Public Sub SaveZip(itm As Outlook.MailItem)
Const saveFolder = "C:\Temp\"
Dim objAtt As Outlook.Attachment
Dim oApp As Object
Dim dName As Variant, unZipFolder
If itm.Attachments.Count > 0 Then
unZipFolder = saveFolder & "unzipped\" & " _
Format(Now,"yyyymmdd_hhmss")
MkDir unZipFolder
For Each objAtt In itm.Attachments
dName = objAtt.DisplayName
objAtt.SaveAsFile saveFolder & dName
Set oApp = CreateObject("Shell.Application")
oApp.NameSpace(unZipFolder).CopyHere _
oApp.NameSpace(saveFolder & dName).Items
Next
End If 'any attachments
End Sub

Email attachment export into specific folder file format issue

I am currently receiving weekly reports on outlook which I need to open and save in a specific folder. I have succeeded in renaming the file and transferring it to the desired file.
HOWEVER, the file format isn't the same as the file which is attached to the email, it is either registered as type "file" when I do not put a date format at the end or a type ".2016" file when I put one. When opened in Notepad the information is unreadable
Here is the code I currently use:
Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim dateFormatdateFormat = Format(Now, "dd.mm.yyyy")
saveFolder = "C:\Users\mypathtotheattachment"
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & "thenewnameofmyattachment" & ".csv"
Next
End Sub
Any help is welcome, I scanned all over the place for any information but I'm stuck...
Thanks!
Is this what your trying to do?
Option Explicit
Public Sub SaveAtmtToDisk(Item As Outlook.MailItem)
Dim Atmt As Outlook.Attachment
Dim SavePath As String
Dim FileName As String
' // Saved Location
SavePath = "C:\temp\"
' // 05 24 2016 Antoine.csv
FileName = Format(Now, "DD MM YYYY") & " Antoine.csv"
For Each Atmt In Item.Attachments
Atmt.SaveAsFile SavePath & "\" & FileName
Next
Set Atmt = Nothing
End Sub
Tested on Outlook 2010

Outlook attachments - Save with Specific Name / Specific type - VBA code

Main problem it only renames the first attachment and I have no control over the other items in the email.
This code saves my attachment and renames it. It works IF the email has only one attachment and no images in signature. If the email comes with one Excel file and an image in signature, it renames the image what I intended to be the Excel file name, and then leaves the Excel file with its original name.
Would be awesome if I can also dictate specific extensions in the save.
Public Sub saveAttachtoDisk_Vendor(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim fso As Object
Dim oldName
Dim file As String
Dim DateFormat As String
Dim newName As String
Dim enviro As String
saveFolder = "S:\Test\"
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
For Each objAtt In itm.Attachments
file = saveFolder & objAtt.DisplayName
objAtt.SaveAsFile file
Set oldName = fso.GetFile(file)
DateFormat = Format(oldName.DateLastModified, "yyyy-mm-dd ")
newName = "Vendor.xls"
oldName.Name = newName
Set objAtt = Nothing
Next
Set fso = Nothing
End Sub
I am toying with these codes but cant get them to work.
validExtString = ".doc .docx .xls .xlsx .msg .pdf .txt" ' <---- Update as needed
validExtArray = Split(validExtString, " ")
And this.
If Right(Atmt.FileName, 3) = "xls" Then
FileName = "C:\Email Attachments\" & Atmt.FileName
Atmt.SaveAsFile FileName
i = i + 1
End If
Be aware, the folder can't contain files with the same name. You need to use different names for attachments.
For Each objAtt In itm.Attachments
The code iterates over all attachments and save them on the disk. It looks like an error in code doesn't allow to get the job done.
I'd recommend running the code in the step-by-step manner (F8) and see what happens in the code running it under the debugger. See Getting Started with VBA in Outlook 2010 for more information.