File Dialog Object

The FileDialog object is a very useful Microsoft Office Object. Believe it or not, you've already seen the FileDialog object in action. Almost all Microsoft Windows applications use some variation of it. In a nutshell, the FileDialog object allows you to display and manage standard Open and Save file dialog windows. An example of the Windows Open dialog window is seen in Figure 11.7.

A Microsoft Windows Open dialog window.

To work with the FileDialog object, you also need to work with the Application object. More specifically, you access the Application object's FileDialog property, which takes a single dialog type parameter. Valid FileDialog property parameters are one of four MsoFileDialogType types:

• msoFileDialogFilePicker. Allows users to select one or more files. Selected files are saved in the FileDialogSelectedItems collection.

• msoFileDialogFolderPicker. Allows the user to select a path. Selected items are saved in the FileDialogSelectedItems collection.

• msoFileDialogOpen. Allows the user to select one or more files to open. Files are opened in the application using the Execute method.

• msoFileDialogSaveAs. Allows the user to select only one file for saving using the Execute method.

The return value of the Application object's FileDialog property should be assigned to your FileDialog object variable.

Set myFileDialog = Application.FileDialog(msoFileDialogOpen)

After doing this, you can use the FileDialog object's Show method to display the specified dialog window. Use a For Each loop and the FileDialog object's SelectedItems property to iterate through each of the user's selections. An example program that uses the FileDialog object is shown next.

Private Sub cmdAddFiles_Click()

'Declare a FileDialog object variable. Dim myFileDialog As FileDialog

'Declare a variant to hold each file selected. Dim vFileSelected As Variant

'Create a FileDialog object as an Open dialog window. Set myFileDialog = Application.FileDialog(msoFileDialogOpen)

'If the user didn't press Cancel, process each selection. If myFileDialog.Show = -1 Then

For Each vFileSelected In myFileDialog.Selectedltems lstFiles.Addltem vFileSelected

Next vFileSelected


'The user pressed Cancel. MsgBox "No files selected."

End If

'Set the myFileDialog object variable to Nothing. Set myFileDialog = Nothing

End Sub

I use the FileDialog object to show an Open dialog window from which the user can select one or more files. Files selected by the user are added to the list box. If the user elects to press Cancel, a message is displayed instead. After finishing with the FileDialog object variable, I set it to Nothing, freeing memory.

0 0

Post a comment