Advertisement
Guest User

VBA

a guest
Jan 27th, 2015
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ' You will need to add a reference to "Microsoft Scripting Runtime" for this to work
  2. ' See http://www.cpearson.com/excel/References.htm for information on how to do this
  3.  
  4. Option Explicit
  5.  
  6. Private fso As New FileSystemObject
  7.  
  8. Sub TestCreateSubDirectories()
  9.     CreateSubDirectories ("D:\..\..\Test1\..\Test1\Test\file.txt")
  10. End Sub
  11.  
  12. Public Function CreateSubDirectories(pathSpec As String)
  13.     Dim pathString As String
  14.    
  15.     ' Sanitise the input
  16.    pathString = fso.GetAbsolutePathName(pathSpec)
  17.    
  18.     If fso.FileExists(pathString) Then
  19.         Exit Function
  20.     End If
  21.    
  22.     If Not fso.DriveExists(fso.GetDriveName(pathString)) Then
  23.         Call Err.Raise(666, "FileUtilities.CreateSubDirectories", "FileUtilities.CreateSubDirectories: Cannot create directory " & pathString & ", there is no " & fso.GetDriveName(pathString) & " drive")
  24.     End If
  25.  
  26.     CreateSubDirectoriesWorker (pathString)
  27. End Function
  28.  
  29. Private Function CreateSubDirectoriesWorker(pathString As String)
  30.     Dim parentPathString As String
  31.    
  32.     If fso.FolderExists(pathString) Then
  33.         ' MsgBox "Path exists, exiting - " & pathString
  34.        Exit Function
  35.     End If
  36.    
  37.     ' MsgBox "Path doesn't exist, recursing to parent - " & pathString
  38.    CreateSubDirectoriesWorker (fso.GetParentFolderName(pathString))
  39.     ' MsgBox "Creating directory " & pathString
  40.    fso.CreateFolder (pathString)
  41. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement