VB script code to save a specific email attachment from a given email

Status
Not open for further replies.

VZZ

New Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
Hi, I'm new to VBA and also this forum. I'm using a simple script code to save email attachments to a Drive folder and name them when they arrive, and activating it within an Outlook rule(run a script), its working fine.......when there is only one attachment in the email. Is there a script modification I can make to save the first attachment only or the fourth attachment only for example if there are multiple attachments in the given email? The code I'm using now cycles through all attachments in a given email and saves the last one, which is not necessarily always the one I need saved-typically its the first one. Thanks for any suggestions
 
You can save a specific # - in place of the variable (often i), enter the number...
objAttachments.Item(3).SaveAsFile strFile

But if you know either the file name or extension you need saved, it would be better to check that as attachment positions have the potential to change.

if right(objAttachments.Item(i).FileName, 4) = "xlsx" then
objAttachments.Item(i).SaveAsFile strFile
end if
 
Thank you Diane, appreciate your quick reply. I will try the # after Item; I thought about looking for the file type but I'm running a variation of the rule on multiple emails that come daily from different senders. Some have 2 or 3 xls or xlsx attachments, but I need to always save the first one(the code is naming the file the same name I specified within the code every time and saving over the previous file on my shared drive....but if multiple attachments are present, it doesn't stop after the first one....the last one ends up being the one saved).

If I decided to try looking for the specific file name to save instead of item #, what would that look like?(some of the files will follow the same naming pattern with current date at the end)
Thanks again
 
Diane, I tried the Item #, but could not get it to work in my below code, could you please show me where I would insert it? Thanks



Code:
Public Sub saveAttachtoDiskRuleNATIONSTARscript(itm As Outlook.MailItem)

Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim fso As Object

Dim file As String
Dim DateFormat As String

Dim enviro As String
enviro = CStr(Environ("XXX"))
saveFolder = enviro & "P:\XXX\"


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



For Each objAtt In itm.Attachments
file = saveFolder & "NationstarBE.xlsx"
objAtt.SaveAsFile file
   
Set objAtt = Nothing
Next
 
Set fso = Nothing
End Sub
 
Diane, Looking for further guidance on this one on my last post, appreciated. Thanks
 
Code:
Public Sub saveAttachtoDiskRuleNATIONSTARscript(itm As Outlook.MailItem)

Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim fso As Object

Dim file As String
Dim DateFormat As String

Dim enviro As String
enviro = CStr(Environ("XXX"))
saveFolder = enviro & "P:\XXX\"


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



For Each objAtt In itm.Attachments
file = saveFolder & "NationstarBE.xlsx"
objAtt.SaveAsFile file
  
Set objAtt = Nothing
Next
 
Set fso = Nothing
End Sub

Hey, you will need to put the "Set objAtt = Nothing" out of the For-Loop. Put it a line before the "Set fso = Nothing"

Cheers,

noobie
 
Thank you for the suggestion, however it didn't seem to do anything different. It still didn't stop after the first attachment and ended up saving the 3rd attachment out of 3.
 
Thank you for the suggestion, however it didn't seem to do anything different. It still didn't stop after the first attachment and ended up saving the 3rd attachment out of 3.

Okay, but that's what Diane already suggested. You will need to specify the number. Also, it may be a tad little bit more complicated than you imagined, but let's try:

The (untested) code that I provide should loop through all the attachments of the MailItem and save the first Excel file it finds.

Code:
Public Sub saveAttachtoDiskRuleNATIONSTARscript(itm As Outlook.MailItem)

Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim file As String
Dim DateFormat As String
Dim enviro As String
Dim oAttachment As Object
Dim i As Long

On Error Resume Next
enviro = CStr(Environ("XXX"))
saveFolder = enviro & "P:\XXX\"

For i = 1 To itm.Attachments.Count
   Set objAtt = itm.Attachments(i)
 
   If Right(objAtt.FileName, 4) = "xlsx" Or Right(objAtt.FileName, 3) = "xls" Then
     file = saveFolder & "NationstarBE.xlsx"
     objAtt.SaveAsFile file
   
     Exit Sub 'or simply write "End"

  End If

  Set objAtt = Nothing 'here, you will need to put the "Set objAtt = Nothing" within the loop.
 
Next i

End Sub
 
Okay, okay, I should note that the End statement will end any procedures :D
So Exit Sub will be the statement you need :)
 
Okay, okay, I should note that the End statement will end any procedures :D
So Exit Sub will be the statement you need :)
Just tested and that worked! Thank you for your help. So, if I wanted to tell it to save excel file item # 3 of 3 attachments for example, I would need to insert 3.......Set objAtt = itm.Attachments(3)?
Thanks again your help is much appreciated.
 
Just tested and that worked! Thank you for your help. So, if I wanted to tell it to save excel file item # 3 of 3 attachments for example, I would need to insert 3.......Set objAtt = itm.Attachments(3)?
Thanks again your help is much appreciated.

It's not always that easy to grab a specific attachment.

Example: the MailItem does have 3 Excel files attached and one screenshot embedded. Now you have 4 attachments in total. And if Outlook does not get the order right, it may be that the screenshot is exactly the attachment #3. Sometimes, you even have attachments that are not visible within the MailItem, but hidden. I had to work trough such stuff myself, and it can be quite frustrating.

Now you have several options:

1) if you're sure that the MailItems do only have Excel files attached, then you can simply skip the For loop and grab attachment #3 (if there are at least 3 Excel files attached; you can check the attachment number with itm.Attachments.Count).

2) if it is not about the 3rd Excel file, but rather the last Excel file to be found, you can rewrite the loop:
For i = 1 To itm.Attachments.Count => For i = itm.Attachments.Count To 1 Step -1 will process it backwards.

3) if it is indeed about the 3rd Excel file, and you also have other attachments within the MailItem, then you will first have to filter for Excel files (i.e. to build an array where you e.g. store the Excel files' file names), and then grab the 3rd argument of the array (or rather the argument #2, as arrays start with 0).

To build a macro for option 3) can be a bit time-consuming, and I don't have a sample code for Outlook that I could provide.
 
Okay, I tried to create such an array. I initially tried to store the attachments themselves within the array, and then just I would just have had to write 'a(2).SaveAsFile file', but that did not work. Hence I had to create some workaround:

1) Move through all attachments and store the file names in the array if the files are Excel files.
2) Get back the third array value as a string (but it is always a(2)='array value #3', as arrays start at 0).
3) Move through all attachments again and check for the file name, and then save as file.

Maybe @Diane Poremsky has a better idea, though :)

Code:
Public Sub saveAttachtoDiskRuleNATIONSTARscript(itm As Outlook.MailItem)

Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim file As String
Dim enviro As String
Dim i As Long
Dim j As Long
Dim a As Variant
Dim chobjAtt As String

On Error Resume Next

Set selItems = Application.ActiveExplorer.Selection

enviro = CStr(Environ("XXX"))
saveFolder = enviro & "P:\XXX\"

file = saveFolder & "NationstarBE.xlsx"

For i = 1 To itm.Attachments.Count
 
    Set objAtt = itm.Attachments(i)
 
            If Right(objAtt.fileName, 4) = "xlsx" Or Right(objAtt.fileName, 3) = "xls" Then
             
                If IsEmpty(a) Then
 
                    a = Array(objAtt.fileName)
 
                Else
             
                    ReDim Preserve a(UBound(a) + 1)
                    a(UBound(a)) = objAtt.fileName
 
                End If
 
            End If
          
Next i

chobjAtt = a(2)

For j = 1 To itm.Attachments.Count

    Set objAtt = itm.Attachments(j)
 
        If objAtt.fileName = chobjAtt Then
     
            objAtt.SaveAsFile file
     
        End If

Next j

End Sub
 
Oh, and I guess you can end the second for loop (with the j's) once you have found the specific attachment; efficiency :D

If objAtt.fileName = chobjAtt Then

objAtt.SaveAsFile file
Exit Sub

End If

It may be problematic when you have several Excel files with exactly the same file name, but well, let's first try it with this one ;)
 
Oh, and I guess you can end the second for loop (with the j's) once you have found the specific attachment; efficiency :D

If objAtt.fileName = chobjAtt Then

objAtt.SaveAsFile file
Exit Sub

End If

It may be problematic when you have several Excel files with exactly the same file name, but well, let's first try it with this one ;)
Wow thank you for spending the extra time and n this, I'll play around with it.
 
You're welcome :)
Just tell me if there are any problems.
 
Status
Not open for further replies.
Similar threads
Thread starter Title Forum Replies Date
R Script for simplifying spam control Outlook VBA and Custom Forms 8
J Outlook Rules VBA Run a Script - Multiple Rules Outlook VBA and Custom Forms 0
N Outlook 2021 'Run Script" Rules? Outlook VBA and Custom Forms 4
K Run a script rule to auto 'send again' on undeliverable emails? Outlook VBA and Custom Forms 1
W Designer Form 2013 and Script ? how ? Outlook VBA and Custom Forms 1
G print attachment straight away; working script edit not working Outlook VBA and Custom Forms 0
G Save attachment run a script rule Outlook VBA and Custom Forms 0
FryW Need help modifying a VBA script for in coming emails to auto set custom reminder time Outlook VBA and Custom Forms 0
G Script does not exist Outlook VBA and Custom Forms 0
G Trigger script without restaring outlook Outlook VBA and Custom Forms 7
A VBA Script - Print Date between first email in Category X and last email in Category Y Outlook VBA and Custom Forms 3
L Modifying VBA script to delay running macro Outlook VBA and Custom Forms 3
L Need help modifying a VBA script for emails stuck in Outbox Outlook VBA and Custom Forms 6
L VB script only runs manually Outlook VBA and Custom Forms 5
E Having some trouble with a run-a-script rule (moving mail based on file type) Outlook VBA and Custom Forms 5
D.Moore VB script to Digitaly Sign newly created outlook message Outlook VBA and Custom Forms 2
Aussie Rules Run a Script on an Incoming Email OK and then the Email reverts Outlook VBA and Custom Forms 0
D.Moore VBA script fail after Office 365 update Using Outlook 8
M Outlook 2013 Script Assistance - Save Opened Link with Subject Added Outlook VBA and Custom Forms 1
F Script for zip file attachment Outlook VBA and Custom Forms 1
S Change VBA script to send HTML email instead of text Outlook VBA and Custom Forms 3
Y Outlook 2013 Run A Script Outlook VBA and Custom Forms 4
Z Script to set account? Using Outlook 0
dweller Outlook 2010 Rule Ignores VBA Script Outlook VBA and Custom Forms 2
N VBA Script to Open highlighted e-mail and Edit Message Outlook VBA and Custom Forms 5
B Outlook rule run a Script doesn't work Outlook VBA and Custom Forms 1
J Calling a Public sub-routine from the script editor via VB script Outlook VBA and Custom Forms 4
K Outlook Archive to PST Files by Date Range VBA Script? Outlook VBA and Custom Forms 1
Peter H Williams Enable script containing VBA Outlook VBA and Custom Forms 12
H VB script in outlook form doesn't work anymore Outlook VBA and Custom Forms 2
A Script to fetch data from mails in restricted collection and sending them to excel Using Outlook 1
B Wanting to run a script that will filter any body that has a russian link in it. Outlook VBA and Custom Forms 5
Bri the Tech Guy Registry Tweak to make "Run a Script" Action Available Outlook VBA and Custom Forms 2
Bri the Tech Guy Run Script rule not running for newly arriving messages Outlook VBA and Custom Forms 25
M Subject Line Automation - Trigger Script Delayed Outlook VBA and Custom Forms 2
Q Script to create a pst file for Archiving Using Outlook 1
Vijay Error in rule- Run a script Using Outlook 1
R VBA Script Quick Parts Using Outlook 1
Vijay Run script doesn't work in outlook Using Outlook 1
Q VBA Script to move item in secondary mailbox Outlook VBA and Custom Forms 2
Diane Poremsky Run a Script Rule: Send a New Message when a Message Arrives Using Outlook 2
F Avoid sending duplicate using Outlook script Outlook VBA and Custom Forms 2
oliv- How to Run a Script IN AN ADDIN with Outlook's Rules and Alerts Outlook VBA and Custom Forms 2
L Run a Script Rule doesn't work Using Outlook 5
N Outlook script to forward emails based on senders' address Outlook VBA and Custom Forms 2
S using script rule to save attachments on arrival Outlook 2010 Outlook VBA and Custom Forms 9
X Outlook script to run excel data Outlook VBA and Custom Forms 1
N VBA Script to Send Automatic Emails from Outlook 2010 Outlook VBA and Custom Forms 1
Davzell Change default pop3 account with script, prf or registery ? Outlook VBA and Custom Forms 0
D RUN SCRIPT WHEN OUTLOOK IS CLOSE Outlook VBA and Custom Forms 1

Similar threads

Back
Top