Cross posted in VBA Express:
http://www.vbaexpress.com/forum/show...335#post336335
I'm working on a project where the user is required to identify a new unique folder name prior to further processing.
If the folder identified already exists processing cannot continue. If the folder identified is invalid (invalid characters or reserved) then processing cannot continue.
The only thing I can think of is:
1) Check if folder exists and
2) Try to create the folder and if it fails ...
I created the following function. Anyone have a better idea?
Code:
Sub Test()
MsgBox fcnIsNewValidFolderName("Test") 'New valid folder name.
MsgBox fcnIsNewValidFolderName("My Documents") 'Existing folder - returns false
MsgBox fcnIsNewValidFolderName("A*B?C") 'Invalid characters in name - returns false
MsgBox fcnIsNewValidFolderName("PRN") 'Reserved name - returns false
lbl_Exit:
Exit Sub
End Sub
Function fcnIsNewValidFolderName(strFolder As String) As Boolean
Dim oFSO As Object, oRootFolder As Object, oFolder As Object
fcnIsNewValidFolderName = True
Set oFSO = CreateObject("Scripting.FileSystemObject")
On Error GoTo Err_Root
Set oRootFolder = oFSO.GetFolder("D:\")
On Error GoTo Err_Create
Set oFolder = oRootFolder.SubFolders(strFolder)
fcnIsNewValidFolderName = False
GoTo lbl_Exit
CreateReEntry:
On Error GoTo Err_Last
'See if a folder can be created using the folder name passed.
Set oFolder = oFSO.CreateFolder(oRootFolder & Application.PathSeparator & strFolder)
oFolder.Delete
lbl_Exit:
Set oFSO = Nothing
Exit Function
Err_Root:
fcnIsNewValidFolderName = True
Resume lbl_Exit
Err_Create:
Resume CreateReEntry:
Err_Last:
Beep
fcnIsNewValidFolderName = False
Resume lbl_Exit
End Function