Selecting multiple files

If the MultiSelect argument for the GetOpenFilename method is True, the user can select multiple files in the dialog box. In this case, the GetOpenFilename method returns an array of filenames. Your code must loop through the array to identify each selected filename, as the following example demonstrates:

Sub

GetImportFileName2()

Dim FileNames As Variant

Dim Msg As String

Dim I As Integer

FileNames =

Application.GetOpenFilename(MultiSelect:=True)

If IsArray(FileNames) Then

Display full path and name of the files

Msg = "You selected:" & vbNewLine

For I = LBound(FileNames) To UBound(FileNames)

Msg = Msg & FileNames(i) & vbNewLine

Next i

MsgBox Msg

Else

Cancel button clicked

MsgBox "No files were selected."

End If

End

Sub

Figure 15-7 shows the result of running this procedure. The message box displays the filenames that were selected.

Figure 15-7:

Select multiple filenames by using the GetOpenFile name method.

Figure 15-7:

Select multiple filenames by using the GetOpenFile name method.

Notice that I use a named argument for the GetOpenFilename method. I set the MultiSelect argument to True. The other arguments are omitted, so they take on their default values. Using named arguments eliminates the need to specify arguments that aren't used.

The FileNames variable is defined as a variant data type. I use the IsArray function to determine whether FileName contains an array. If so, the code uses the VBA LBound and UBound functions to determine the array's lower and upper bounds and build a message that consists of each array element. If FileNames is not an array, the user clicked the Cancel button. Remember that the FileNames variable contains an array even if only one file is selected.

0 0

Post a comment