Solved

Can you create a VBA macro that checks if folder exists and if not creates one

Posted on 2016-10-13
9
64 Views
Last Modified: 2016-10-19
I am trying to create a macro that saves down a file to a folder with the corresponding month and year.

i.e. S:2016\10-Oct 2016

If the folder doesn't exist I then want the macro to create one.

Is this even possible?
0
Comment
Question by:Benjamin Hopper
  • 3
  • 2
  • 2
  • +2
9 Comments
 
LVL 27

Expert Comment

by:MacroShadow
ID: 41841979
Not sure what you meant by
saves down a file to a folder with the corresponding month and year
But the following code will create the folder defined in the strFolderPath variable if it doesnt already exist.
Option Explicit

Private Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" (ByVal lpPath As String) As Long
Sub Demo()
    Dim strFolderPath As String
    strFolderPath = "C:\2016\10-Oct 2016\"
    If Dir(strFolderPath, vbDirectory) <> vbNullString Then
        MakeSureDirectoryPathExists strFolderPath
    End If
End Sub

Open in new window

0
 
LVL 35

Expert Comment

by:Kimputer
ID: 41841997
I think that code works, but only if you change <> to =
0
 
LVL 27

Expert Comment

by:MacroShadow
ID: 41841999
oops ;-)
0
 
LVL 52

Expert Comment

by:Bill Prew
ID: 41842038
If you know the parent folder will exist, then you can create the new date based child pretty simply like below.  In addition, if wanted a little more control over things then you could use the FileSystemObject as well, happy to share an example of that as well...

strDir = "S:\2016\10-OCT-2016\" 
If Dir(strDir, vbDirectory) = "" Then MkDir strDir

Open in new window

~bp
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 17

Expert Comment

by:Roy_Cox
ID: 41842169
Maybe you want the name to be dynamic
Option Explicit

Public Sub TestFolderExists()
 Dim sFullPath As String
 
 sFullPath = "S:" & Year(Date) & Application.PathSeparator & Format(Date, "dd-mmm yyyy")
 If Not Dir(sFullPath, vbDirectory) = vbNullString Then
        MsgBox sFullPath & " exists!"
    Else: MkDir (sFullPath)
    End If

End Sub

Open in new window

0
 
LVL 35

Expert Comment

by:Kimputer
ID: 41842208
I still like the first solution better (because creating the subfolder is not depended on parent folder's existence, and therefore more fool proof). The asker might have a hard time figuring out this problem right after new year's eve.
0
 
LVL 2

Expert Comment

by:Antonio Salva Ripoll
ID: 41844031
Hi.

Please, be patient if my English language level is not so good.

Try this:

Dim fso As Scripting.FileSystemObject
    Dim ArrPath As Variant
    Dim n As Integer
    
    Dim sFullPath As String
    
    Set fso = New Scripting.FileSystemObject
    
    sFullPath = CurrentProject.Path & "\" & Year(Date) & "\" & Format(Date, "dd-mmm yyyy")

    ArrPath = Split(sFullPath, "\")
    
    sFullPath = ArrPath(0)
    
    For n = 1 To UBound(ArrPath)
        sFullPath = sFullPath & "\" & ArrPath(n)
        If Not fso.FolderExists(sFullPath) Then
            fso.CreateFolder (sFullPath)
        End If
    Next n
    Set fso = Nothing  

Open in new window


You only require a reference to Microsoft Scripting Host (included) and doesn't need any external library.

This routine hasn't problems if the full path not exists, because checks/create the full path.


Also, if you are using a network drive, you can check this and use the real network resource (ServerName\Root Path) instead of mapped names by using the Scripting. FileSystemObject .


Best regards.

Antonio.
Barcelona (Spain).
0
 
LVL 17

Accepted Solution

by:
Roy_Cox earned 500 total points
ID: 41844705
Please disregard my previous answer, I posted the wrong code.

This is the code that I meant to post. It will create a Name in the Excel workbook that is created which is used to check if the workbook is a copy. This way you do not need to remove all the code in the workbook

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim bCopy As Boolean
    Const SaveAsPath = "C:\Users\pike\Desktop\backup\"
    Cancel = True
    On Error Resume Next
    bCopy = Evaluate(ThisWorkbook.Names("Copy").RefersTo)

    If bCopy Then
        ThisWorkbook.Close True    ''??? True will ensure the workbook is saved before closing
    Else
        Select Case MsgBox("Would you like to create a backup copy?", vbYesNo _
            Or vbQuestion Or vbDefaultButton1, "Create Copy")
        Case vbYes
            ActiveWorkbook.SaveAs SaveAsPath & ThisWorkbook.Name & Format(Date, _
                "ddmmyyyy") & ".xlsm", FileFormat:=52
            ''/// set the flag is the Name
            ThisWorkbook.Names.Add Name:="Copy", RefersTo:=1, Visible:=True
        Case vbNo
        End Select
        End If
        On Error GoTo 0
    End Sub

Open in new window

0
 
LVL 17

Expert Comment

by:Roy_Cox
ID: 41850572
Pleased to help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Improved? Move/Copy Add-in Replacement - How to avoid the annoying, “A formula or sheet you want to move or copy contains the name XXX, which already exists on the destination worksheet.” David Miller (dlmille)  It was one of those days… I wa…
Workbook link problems after copying tabs to a new workbook? David Miller (dlmille) Intro Have you either copied sheets to a new workbook, and after having saved and opened that workbook, you find that there are links back to the original sou…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now