Visual Basic Macro for Outlook

jdarville

New Member
Joined
Dec 4, 2012
Messages
4
Good Morning,

The code below will look for at incoming emails and create a folder in desired location for each attachment automatically. It names the folders whatever the attached file is but i actually need it to label the folders with the name of the sender.

Example, if i get an email with an attachment from joeshoem@thecompany.com i want the script to create a folder called thecompany and save the attached file in that folder. That's the ultimate gold but i can settle with joeshoem@thecompany.com as the folder name as well.



Code:
Sub SaveAttachments_VariableFolder(MyMail As MailItem)

Dim Atmt As attachment

Dim FileName As String
Dim lenName As Long
Dim strPathAdd As String

Const strPath As String = "C:\test\" ' set as desired

On Error Resume Next
MkDir strPath
On Error GoTo 0

For Each Atmt In MyMail.Attachments

    If (Right(Atmt, Len(Atmt) - InStrRev(Atmt, "."))) = "pdf" Then
    
        lenName = InStrRev(Atmt, ".") - 1
            
        ' Trim possible spaces before the extension.
        ' A space at the end of the name created a problem with deleting the folder
        strPathAdd = strPath & Trim(Left(Atmt, lenName)) & "\"
            
        On Error Resume Next
        MkDir strPathAdd
        On Error GoTo 0

        FileName = strPathAdd & Atmt.FileName
        Atmt.SaveAsFile FileName
        
    End If
    
Next Atmt

Set Atmt = Nothing
    
End Sub
 

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.

Forum statistics

Threads
1,225,635
Messages
6,186,128
Members
453,340
Latest member
Stu61

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top