31 Using File Dialog Boxes
31 Using File Dialog Boxes
31 Using File Dialog Boxes
Introduction
You can use the built-in dialog boxes in VBA to ask users to choose files and folders. An
example of a custom dialog box for opening files is shown below:
You can set a custom title
for the dialog box.
You can specify the initial
folder to look in.
You can choose which view
to display the files in.
You can customise the file
filters and choose the one
that should be applied by
default.
You can change the default
text on the action button.
Wise
Wise Owls
Owls
Hint
Hint
Copyright 2015
The exact style of the dialog box that you see will depend on which
operating system you are using. The example above is from Windows
Vista.
Page 35
4.2
The easiest and most flexible way to open and save files in VBA is to use the FileDialog
property there are four types of dialog box you can use:
This is by far the easiest
way to open and save
files, and to choose files
and folders.
What it does
msoFileDialogFilePicker
msoFileDialogFolderPicker
msoFileDialogOpen
msoFileDialogSaveAs
You can display one of the four types of dialog boxes as shown below:
Copyright 2015
Page 36
4.3
Customising FileDialogs
There are many ways in which you can change how the file dialog boxes appear, as described
under separate headings below.
Choosing an Initial View
You can choose to display your files/folders as icons, thumbnails, etc initially:
Use this property to set the
initial view (see the possible
options below).
Wise
Wise Owls
Owls
Hint
Hint
Copyright 2015
Users of Windows Vista may find that changing the initial view of a file
dialog box has no effect when the code runs.
Page 37
Setting Filters
Whenever a dialog box appears for opening files, you can control which files you can look for:
Here we have two filters the first
of which is selected by default.
Each filter has a name, a file extension and a position in the list. for our example, the filters are:
Name of filter
Extension
Position
*.wol
All Files
*.*
Copyright 2015
Page 38
Copyright 2015
Page 39
4.4
Examples
Despite this apparent difference, you can use the Open and SaveAs dialog boxes to choose a file
or folder just dont apply the Execute method afterwards.
Finding Out which File was Chosen
A file dialog box has a SelectedItems() property, giving an array of the files chosen. Also, when
you apply the Show method you can get back one of two values:
Value
What it means
-1
The user chose Cancel or closed the dialog box without doing anything.
You can put all this information together to find out the file a user chose, as in this example:
This command states that a user will only be able
to select a single file.
If the user
chooses a
single file:
Copyright 2015
Page 40
Copyright 2015
Page 41
4.5
Wise
Wise Owls
Owls
Hint
Hint
Copyright 2015
Page 42