|
|
|
|
|
|
Multiple Apps
|
Determine if a folder exists using the File System Object (FSO)
|
|
Ease of Use
|
Intermediate
|
Version tested with
|
2003
|
Submitted by:
|
xCav8r
|
Description:
|
When given a Windows path to a folder, this function returns true if it exists; false, if it doesn't.
|
Discussion:
|
An easy way to avoid errors is to check if a folder exists before trying to save or move a file there. This function uses the File System Object to determine if the folder exists or not.
This is an alternative to kplus' KB entry entitled "Check if directory or file exists." His function arrives at the same result, but without the File System Object. His also supports macintosh paths. (http://www.vbaexpress.com/kb/getarticle.php?kb_id=559)
This is related to another KB entry entitled "Test if a file exists using the File System Object". (http://www.vbaexpress.com/kb/getarticle.php?kb_id=635)
NB: This will not work on the Macintosh.
|
Code:
|
instructions for use
|
Option Explicit
Private Const mcstrValidPathToFolder As String = "C:\temp"
Private Const mcstrInvalidPathToFolder As String = "C:\temp2"
Private Sub TestMyFolderExists()
Debug.Print MyFolderExists(mcstrValidPathToFolder)
Debug.Print MyFolderExists(mcstrInvalidPathToFolder)
End Sub
Public Function MyFolderExists(Path As String) As Boolean
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Select Case objFSO.FolderExists(Path)
Case True
MyFolderExists = True
Case False
MyFolderExists = False
End Select
Set objFSO = Nothing
End Function
|
How to use:
|
- Open your document.
- Press Alt + F11 to open the Visual Basic Editor (VBE).
- Insert a standard module. (Insert -> module)
- Paste the code in the window to the right. (F7 to view; CTRL + V to paste)
- Save the file.
|
Test the code:
|
- From the VBE, make sure the Immediate Window is visible (CTRL + G)
- With your cursor anywhere in the module, press F5. (If your cursor is in the TestMyFolderExists sub procedure, then you won't have to do the next step.)
- Select TestMyFolderExists from the dialog box that appears, and then click Run.
|
Sample File:
|
TestFolderExistsWithFSO.zip 9.54KB
|
Approved by mdmackillop
|
This entry has been viewed 124 times.
|
|