Guidelines When Working With Files and Folder
Guidelines When Working With Files and Folder
Guidelines When Working With Files and Folder
If you want to work with files or the file system then there a various options available.
VBA Functions - These are the built-in functions and procedures.
File System Object - This uses an additional library called the Microsoft Scripting Run-time
vbReadOnly 1
vbHidden 2
Important
When using strings of folderpaths and files they are not case sensitive. Always check the server folder is
available first if not display a polite message. Always check the folder actually exists and check the access
permission with sensible error messages if user does not have permission.
Always use the UNC folderpath classifications. No hard typing of drive letters - always use full name (
\\server\path\ ). Never refer to mapped drives. When using folders always check they exist and check the
permission with sensible error messages.
The FileSearch object can be used as an alternative to using the Dir() function. This is available in Office 97,
but has been enhanced significantly in Office XP.
Browsing To
To display a folder location or file location you use the combobox control.
By changing the "DropButtonStyle" to fmDropButtonStyleEllipsis we can create a control that resembles a
filename box.
'toggle the enabled property to move the focus to the next control
Me.cboFileName.Enabled = False
Me.cboFileName.Enabled = True
End Sub
One annoying aspect of hooking the DropButtonClick event is that we can't cancel it so the control shows an
empty list after we have obtained the filename.
One workaround it to toggle the Enabled property of the control which forces the focus to move to the next
control in the tab order.
This is an additional library that offers clear, object-orientated access to all the common file and directory
functions.
This object is not part of the Office library and requires you to add an additional reference to your project.
SS - References dialog
Once the reference has been added you can use the Object Browser to find out more about the objects.
The Microsoft Scripting Runtime is a library that can be added to a Project using (Tools > References).
This library is located in C:\Windows\System32\scrrun.dll
Application.GetOpenFileName
Application.GetOpenFileName
Can be used to obtain a valid filename and its full path.
This method displays the Open dialog box but will not actually open the file.
This method will return a string value specifying the path and filename that was selected.
sFullPath = Application.GetOpenFileName(FileFilter,FilterIndex,Title,ButtonText,MultiSelect)
FileFilter - This determines the types of files that will be displayed in the Files Of Type drop-down list. This
argument consists of pairs of the file filter display text followed by the wildcard file filter specification. Each
pair seperated by commas. The default is "User (*.*), *.*"
FilterIndex - This specifies which file filter is the default. Not required if there is only one filter provided.
Title -
ButtonText - This argument is not used in Excel for Windows.
MultiSelect - Determines if the user can select multiple files. If you allow multiple files to be selected you
can use the IsArray() function to check if multiple files were selected.
sFullPath = Application.GetOpenFileName()
When you want to filter the choice to specific file extensions you must use the following format:
"description,*.extension"
The following line of code will display a dialog box allowing you to select an XML file.
Sub DisplayFileOpen
Dim sFilter As String
Dim vaFile As Variant
Application.FindFile
Excel
Displays the (File > Open) dialog box allowing the user to choose a file to open.
This only lets the user select a file - This doesn't let you return the file name (and path) of the file that is
selected
Returns True if the file opens successfully.
If the user cancels the dialog box, then False is returned
Application.FindFile
Application.GetSaveAsFileName
Excel
sFullPath = Application.GetSaveAsFileName
PowerPoint
Does not exist
Application.Dialogs
The following line of code can be used to display any of the built-in dialog boxes.
bResult = Application.Dialogs(xlBuiltinDialog.xlDialogActivate).Show
The result returned is True if the user clicked OK and False if the user pressed Cancel.
Most of the buil-in dialog boxes accept arguments which correspond to the controls on the dialog box.
You cannot use named arguments when passing parameters to these dialog boxes.
Attempting to display a built-in dialog box in an incorrect context will result in an error.
The dialog box for selecting, changing and inputing database records is ShowDataForm.
Include the "Built-in Dialog Box Arguments List" from the VBA help file
Excel
You can use the dialogs property with the wdDialogFileOpen constant to return a dialog object that refers to
the (File > Open) dialog box.
The Show method displays and executes the action.
The Display method just displays the dialog box, allowing the user to check the controls before executing.
Application.FileDialog
Added in Office 2002.
This provides a single object that allows you to display the (File > Open) and (File > Save As) dialog boxes.
This is a much more powerful version of the previous GetOpenFileName and GetSaveAsFileName
One advantage of this FileDialog object is that you can display a list of just directories, rather than both
directories and files.
This also has the advantage of being available in all the Office applications.
The Office prefix is not required but it makes it clear that it is an object in the Office library.
Application.FileSearch
Application.FileSearch
The FileSearch object basically gives you all the functionality of the (File > Open) dialog box
You can use FileSearch instead of using the earlier Dir() function.
Types of Objects
FileTypes - In 97 and 2000 you could only specify a single FileType property. Office 2002 introduced a
FileTypes collection that allows you to specify multiple file types.
FoundFiles collection - All the matching file names are placed in this collection.
PropertyTests -
SearchScopes collection - (Added 2002)
ScopeFolders - (Added 2002)
SearchFolders - (Added 2002)
Example
If objFileSearch.Execute(msoSortBy.msoSortbyFileName, _
msoSortOrder.msoSortOrderAscending) > 0 Then
For iFileCount = 1 To objFileSearch.FoundFiles.Count
Next iFileCount
Else
Call MsgBox ("There were no files found.")
End If
FileName specifies the name of the file to be found (wildcards can be used)
FoundFile Returns a FileSystem object that contains the names of the files that have been
found
NewSearch Resets the FileSearch object to its default settings. All property values are
retained after each search is run, and by using the NewSearch method you can
selectively set properties for the next file search without manually resetting
previous property values.
With Application.FileSearch
.LookIn = "C:\"
.FileName = ""
If .Execute(msoSortByLastModified, _
msoSortOrderDescending, True) > 0 Then
sfullname = .FoundFiles(1)
End If
End With