Here are differences I have sorted out, starting from the idea FileDialog
gives an object to set up and retrieve results from, while GetOpenFileName
gives a one-and-done function.
a. File Dialog has more options. These include:
- pre-setting a filename for when the dialog opens (
InitialFileName
property)
- changing the names of the button (
ButtonName
property)
- changing how the files are shown (
InitialView
property)
- an
Execute
method to actually open or save the file that's been selected.
b. GetOpenFilename goes with GetSaveAsFilename.
The difference between these two is also confusing at first, until you realize that you can't change the button caption (unless possibly on a Mac). That means you can change the title, but the button will still say "Open" or "Save". If you are picking files for other reasons, FileDialog lets you set the button to a custom string.
c. File Dialog Types. While FileDialog leaves more to the user, it has basic setups by use of the single fileDialogType argument:
set fd = Application.FileDialog(msoFileDialogFilePicker)
set fd = Application.FileDialog(msoFileDialogFileOpen)
set fd = Application.FileDialog(msoFileDialogSaveAs)
Each gets you the same object (see the next bullet), but with different properties. Most important is the DialogType property, which is then read-only, and can be changed only via a new set
statement. This property determines what happens with .Execute: open, save, or for msoFileDialogPicker, an error. Other properties are set to match the initializing fileDialogType argument, but can generally be changed before you call .Show
.
d. File Dialog quirks. With the FileDialog
object, it turns out that you have just one per application. That means if you try to think ahead with set fdo = Application.FileDialog(msoFileDialogOpen)
to open files and then set fdsa = Application.FileDialog(msoFileDialogSaveAs)
to save files, hoping to keep both for later use, you'll soon learn that fdo and fdsa refer to the same object, now with the msoFileDialogSaveAs settings. The lesson is to set the parameters just before you use it.
e.) Getting the results. For the GetOpenFilename
and GetSaveAsFilename
methods, since they operate as functions, you get the selection as a return value. The return value may be a single selection, an array, or False
if the user clicked Cancel. For the FileDialog
object, in contrast, you get results through a SelectedItems collection as a property of the object. If a user clicked Cancel, the count will be 0, and the .Show method also returns -1. The latter is used in the pattern if fd.Show then fd.Execute
, often in a with
block.
Based on these, I think I'll stick with the file dialog. It can also pick folders, so it's probably a good one to be familiar with.
FileDialog
is a property of Application that returns a FileDialog object.GetOpenFilename
is a method of Application that displays the standard Open dialog box.GetOpenFilename
is Excel only. – Tanguay