Guidelines When Working With Files and Folder

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Files & Directories

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

Guidelines when working with Files and Folder


All folder conventions should be: \2010\February\2010_Feb_24.xls
Need generic code to always get a file from a folder and if the file does not exist then automatically search
the "archive" sub folder.
All folder paths should be UNC standard \\server\share [never use mapped letters]
When opening files from folders always check for permission and if not display a sensible error message
Code to analyse a folder and get the data from the last saved down file.
Be able to look for previous dates in order.

File Attribute Constants

vbNormal 0 Normal, default for Dir & SetAttr

vbReadOnly 1  

vbHidden 2  

vbSystem 4 System file

vbVolume 8 Volume label

vbDirectory 16 Directory or Folder

vbArchive 32 File has changed since last backup ??

vbAlias 64 Identifier is an alias

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.

You can then hook the DropButtonClick event.

Private Sub cboFileName_DropButtonClick()


   Dim vFileName As Variant

'get the filename


'write it to the control
   Me.cboFileName.Text = vFileName

'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.

File System Object

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

Dim objFSOFileSystemObject As Scripting.FileSystemObject


Set objFSOFileSystemObject = CreateObject("Scripting.FileSystemObject")

Application.GetOpenFileName

Excel - (File > Open) dialog box


SS
This should not be used but is still available in backwards compatibility.

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.

All the arguments are optional.

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.

sFullPath = Application.GetOpenFileName(FileFilter:="Excel Files (*.xlsx),*.xlsx", _


                          Title:="Please select an Excel file")
If Len(sFullPath) = 0 Then
   MsgBox("No file selected")
End If

Return Value = Variant


The value this function retuns must be assigned to a variant.

Sub DisplayFileOpen
Dim sFilter As String
Dim vaFile As Variant

'build a filter list


'if you omit the space before the first comma excel will not display the pattern, (*.New)
      sFilter = "New Files (*New) ,*.new," & _
                "Old Files (*Old) ,*.old," _
                "All Files (*.*) ,*.*"

'display the file open dialog putting the result in a variant


   vaFile = Application.GetOpenFileName(FileFilter:=sFilter, _
                                        FilterIndex:=1, _
                                        Title:="Open a New or an Old File", _
                                        MultiSelect:=False)

'did you press Cancel?


   If vaFile <> False Then
      MsgBox "You want to open " & vaFile
   End If
End Sub

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(InitialFilename, FileFilter, FilterIndex, Title,


ButtonText)

All the arguments are optional.

sFullPath = Application.GetSaveAsFileName

This method is still available for backwards compatibility

If the user cancels, this method returns False


If multiselect is False, this method returns a String
If multiselect is True, this method returns a String Array
Word
Does not exist

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

Dim objDialog As Dialog

For some reason the following line does not work ??

'Dim objDialog As Application.Dialog


Set objDialog = Application.Dialogs(xlBuiltInDialog.xlDialogOpen)

For some reason the following line doesn't work

'Set objDialog = Dialogs(xlBuiltInDialog.xlDialogOpen)


objDialog.Show

Include a table of all the parameters from the VBA help


Word

Dim objDialog As Dialog


   Set objDialog = Dialogs(wdDialogFileOpen)

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.

Dim objDialog As Dialog


   Set objDialog = Dialogs(wdDialogFileOpen)
   bReturn = objDialog.Display
   sFileName = objDialog.Name
   If bReturn = -1 Then
      Documents.Open FileName:=sFileName
   End If

For more info see the help file.

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.

Set objFileDialog = Application.FileDialog(msoFileDialogType.msoFileDialogOpen)

Types of Dialog Box


There is very little difference between the four types except the caption displayed at the top of the dialog
box.
The FilePicker and FolderPicker display the word "Browse" in the caption while the other two display "File
Open" and "File Save As".
They all display directories and files except the FolderPicker.

Set objFileDialog = Application.FileDialog(msoFileDialogType.msoFileDialogOpen)

The Office prefix is not required but it makes it clear that it is an object in the Office library.

Public Sub File_Dialog_Test


Dim objFileDialog As Office.FileDialog
Dim objFileDialogFilters As Office.FileDialogFilters
Dim sFileName As String

   Set objFileDialog = Application.FileDialog(msoFileDialogType.msoFileDialogOpen)


   With objFileDialog

'define a Filters object


      Set objFileDialogFilters = .Filters
      With objFileDialogFilters

'clear the default filters


         .Clear
         
'add a filter, all filters must start with an asterisk
         .Add "Client Files", "*.xls"
         .Add "Images", "*.png,*.jpg", 1
         .Add "All Files", "*.*"
      End With

'allow only one file to be selected


      .AllowMultiSelect = False

'show the dialog and exit if Cancel is pressed


      If .Show = False Then
         Exit Sub
      End If
'display the file name that was selected
      Call Msgbox("File selected : " & .SelectedItems(1))
   End With
End Sub

Displaying the Dialog Box


The Show method will display the dialog box.
This method will not actually open the files but just adds the selection to the SelectedItems collection.
If the user clicks Open then "True" is returned.
If the user clicks Cancel then "False" is returned.
You can use the Execute method to actually open or save the files.

If .Show = True Then


   .Execute
End If

Application.FileSearch

Removed in Office 2007


Office 97 introduced a FileSearch object (enhanced in 2002) that allows you to search and maintain files
easily.
This allows you to search for files with a wide range of search criteria such as file type, file size, file location
and date of last modification.
This object can be found in the Office library.

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

Dim iFileCount As Integer


Dim objFileSearch As Variant

Set objFileSearch = Application.FileSearch


objFileSearch.LookIn = "C:\Temp\"
objFileSearch.FileType = msoFileType.msoFileTypeExcelWorkbooks

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

Key Properties and Methods

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

LookIn Specifies the directory to be searched

SearchSubFolders Returns True if subdirectories are to searched

Execute Performs the search

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.

Any files found are placed in a FoundFiles collection

Private Sub SearchAFolder()


Dim sfolderpath As String
Dim sextension As String
Dim objfilesearch As Variant
Dim vobjfile As Variant
Dim sfullname As String
   
   Set objfilesearch = Application.FileSearch
   
   With objfilesearch
      .NewSearch
      .LookIn = "C:\Temp\"
      .SearchSubFolders = False
      .FileType = msoFileType.msoFileTypeAllFiles
      .LastModified = msoLastModifiedToday
      .Execute
      
'for each control variable must be variant or object
      For Each vobjfile In .FoundFiles
         sfullname = CStr(vobjfile)
         If Right(sfullname, 3) = ".bmp" Then
         End If
      Next vobjfile
      
   End With
End Sub

List all the files in the root directory

Private Sub FileFinder()


Dim objFile As Variant
   With Application.FileSearch
      .LookIn = "C:\"
      .FileType = msoFileType.msoFileTypeAllFiles
      .Execute
      For Each objFile in .FoundFiles
         Call MsgBox(objFile)
      Next objFile
   End With
End Sub

Return most recent file from a folder

Dim sfullname As String

   With Application.FileSearch
      .LookIn = "C:\"
      .FileName = ""
      If .Execute(msoSortByLastModified, _
                  msoSortOrderDescending, True) > 0 Then
          sfullname = .FoundFiles(1)
      End If
   End With

You might also like