Hi,
I used to have a really useful vba Function to check for & create folders when passed a string (filepath), but I seem to have mislaid it. Could anyone offer me a pointer to similar?
Thanks
vba Function to check for & create folders
-
- 5StarLounger
- Posts: 1185
- Joined: 24 Jan 2010, 12:02
- Location: Wales, UK.
vba Function to check for & create folders
Nathan
There's no place like home.....
There's no place like home.....
-
- 2StarLounger
- Posts: 112
- Joined: 25 Jan 2010, 20:19
Re: vba Function to check for & create folders
Code: Select all
Sub makeDir()
If Dir("C:\TestFolder", vbDirectory) = "" Then
MkDir "C:\TestFolder"
End If
End Sub
-
- Administrator
- Posts: 78629
- Joined: 16 Jan 2010, 00:14
- Status: Microsoft MVP
- Location: Wageningen, The Netherlands
Re: vba Function to check for & create folders
I once posted a macro in Woody's Lounge, but it was mangled during the conversion to the new software.
Here is the corrected version:
Use like this:
CheckFolder "C:\Reports\Sales\Monthly\March"
or
CheckFolder "\\MyServer\MyShare\MyFolder\Documents"
Here is the corrected version:
Code: Select all
Sub CheckFolder(strPath As String)
Dim fso As Object
Dim intPos As Integer
Dim intLen As Integer
intLen = Len(strPath)
Set fso = CreateObject("Scripting.FileSystemObject")
If Left(strPath, 2) = "\\" Then
' UNC path - skip server and share
intPos = InStr(3, strPath, "\")
intPos = InStr(intPos + 1, strPath, "\")
Else
' drive letter - skip C: part
intPos = 3
End If
Do
intPos = InStr(intPos + 1, strPath, "\")
If intPos = 0 Then
intPos = intLen + 1
End If
If fso.FolderExists(Left(strPath, intPos - 1)) = False Then
fso.CreateFolder Left(strPath, intPos - 1)
End If
Loop Until intPos = intLen + 1
Set fso = Nothing
End Sub
CheckFolder "C:\Reports\Sales\Monthly\March"
or
CheckFolder "\\MyServer\MyShare\MyFolder\Documents"
Best wishes,
Hans
Hans
-
- 5StarLounger
- Posts: 1185
- Joined: 24 Jan 2010, 12:02
- Location: Wales, UK.
Re: vba Function to check for & create folders
Thanks a lot for this.
Out of interest, is there any reason why this is s sub as opposed to a function?
Out of interest, is there any reason why this is s sub as opposed to a function?
Nathan
There's no place like home.....
There's no place like home.....
-
- Administrator
- Posts: 78629
- Joined: 16 Jan 2010, 00:14
- Status: Microsoft MVP
- Location: Wageningen, The Netherlands
Re: vba Function to check for & create folders
Because it doesn't return a value. You could make it a function if you prefer...
Best wishes,
Hans
Hans