You can use the
Folders.Add method [
^] method to create the folders either based on
Now
or on Outlook.MailItem.CreationDate (the latter might be useful if you want to retrospectively move stuff)
If I've misunderstood, and it's a folder on your C: drive you want to create then you can use the
MkDir statement[
^]
Edit: Other functions you might find useful
FolderExists method [
^]
Folders object (Outlook) [
^]
Edit - some actual code
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim dateFormat As String
dateFormat = Format(itm.CreationTime, "yyyy-mm-dd")
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim getsender As String
saveFolder = "C:\Users\UserName\Desktop\Attachments\" & dateFormat & "\"
CreateFolderIfNotExists saveFolder
For Each objAtt In itm.Attachments
If InStr(objAtt.FileName, ".pdf") > 0 Then
objAtt.SaveAsFile saveFolder & objAtt.DisplayName
End If
Next
End Sub
Public Sub CreateFolderIfNotExists(folderName As String)
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.folderexists(folderName) Then
fs.createfolder (folderName)
End If
End Sub
Points to note - see the comment points in the code:
Comment 1:
I've explicitly given
dateFormat
a type. I believe that to be best practice
Comment 2:
I've used the date that the email was created - this will allow you to retrospectively save attachments for older emails in the correct folders. Note the difference in the format I have used compared to yours.
Comment 3:
I've added the appropriate date to the
saveFolder
name
Comment 4:
I've put the code to check for a folder and create it into a separate subroutine
Comment 5:
There is no need to set
objAtt
to Nothing after saving the PDF. It will be reassigned by the loop immediately afterwards. You exit the sub after the loop is complete so it will go out of scope and eventually be cleared out of memory anyway.
Comment 6:
I suggested using
MkDir
in my original answer, but I already have a
FileSystemObject
so I've used
CreateFolder
instead here.
Another Edit!
Here is a snippet of code that will get all items in your inbox and dump the sender details to the Immediate window
Dim objMails As Outlook.Items
Set objMails = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Items
Dim objMail As Outlook.MailItem
For Each objMail In objMails
Debug.Print objMail.Sender, objMail.SenderEmailAddress
Next