Get OpenFilename example

The fileFilter argument determines what appears in the dialog box's Files of Type drop-down list. This argument consists of pairs of file filter strings followed by the wild card file filter specification, with commas separating each part and pair. If omitted, this argument defaults to the following:

Notice that this string consists of two parts:

The first part of this string is the text displayed in the Files of Type dropdown list. The second part determines which files the dialog box displays. For example, *.* means all files.

The code in the following example brings up a dialog box that asks the user for a filename. The procedure defines five file filters. Notice that I use the VBA line continuation sequence to set up the Filter variable; doing so helps simplify this rather complicated argument.



Dim Finfo As String

Dim Filterlndex As Integer

Dim Title As String

Dim FileName As Variant

Set up list of file filters

FInfo = "Text Files (*.txt),*.txt," & _

"Lotus Files (*.prn),*.prn," & _

"Comma Separated Files (*.csv),*.csv," & _

"ASCII Files (*.asc),*.asc," &

"All Files (*.*),*.*"

Display *.* by default

FilterIndex = 5

Set the dialog box caption

Title = "Select a File to Import"

Get the filename

FileName = Application.GetOpenFilename(FInfo, _

FilterIndex, Title)

Handle return info from dialog box

If FileName = False Then

MsgBox "No file was selected."


MsgBox "You selected " & FileName

End If



Figure 15-6 shows the dialog box Excel displays when you execute this procedure. In a real application, you would do something more meaningful with the filename. For example, you may want to open it by using a statement such as this:

Workbooks.Open FileName

Notice that the FileName variable is declared as a variant data type. If the user clicks Cancel, that variable contains a Boolean value (False). Otherwise, FileName is a string. Therefore, using a variant data type handles both possibilities.

Figure 15-6:

GetOpenFile name method displays a customizable dialog box and returns the selected file's path and name. It does not open the file.

0 0

Post a comment