Ramesh
Ramesh

Reputation: 3

VBA in Outlook 2007 - how do I create a new folder if one doesn't already exist

I am writing a script that saves file attachments to a folder. I want to create sub-folders if they don't already exist. Is there a quick way of doing this? Essentially I am looking for something along the lines of:

If folder exists, then do nothing. Else, create folder. End if.

I know this is a silly 2 line piece of code, but any help much appreciated! I'm using the SaveAsFile method within Outlook.MailItem.Attachments so perhaps there is a quick way of using another function which does the same? Thanks again!

Excerpt from my current script below:

' Time stamp it dateFormat = Format(Now, "yyyy-mm-dd hh-mm ")

' Save folder
saveFolder = centrallocation & ticker & "\"

For Each objAtt In itm.Attachments
    ' File extension
    extension = Right(objAtt.FileName, Len(objAtt.FileName) - InStrRev(objAtt.FileName, "."))
    extension = LCase(extension)

    If extension = "xlsx" Or extension = "xls" Or extension = "xlsxm" Or extension = "xlsm" Then
        saveFolder = saveFolder & "\Model\"
        objAtt.SaveAsFile saveFolder & dateFormat & objAtt.DisplayName
    Else
        objAtt.SaveAsFile saveFolder & dateFormat & objAtt.DisplayName
    End If

    ' go to next attachment
    Set objAtt = Nothing
Next

Upvotes: 0

Views: 3179

Answers (1)

mr_plum
mr_plum

Reputation: 2437

Call this before saving your file:

Sub CreateFolderIfMissing(path as String)

    Dim folderExists As Boolean
    folderExists = (Dir(path) <> "")

    If (folderExists) Then Exit Sub

    MkDir path
End Sub

Upvotes: 1

Related Questions