Link to home
Start Free TrialLog in
Avatar of keschuster
keschuster

asked on

VBA FileDialog - Set Multiple Selected Files to Array

I'm trying to enable this code for file picker to select multiple file and return all of the filename.  I've used this code for sometime to return one file.  I'm trying to enable multiselect so I can return a list of selected files.

Can someone help me get there?

Public Function modImportExport_OpenFile(strFileExtension As String, Optional bolAllowMultiSelect As Boolean = False)
    ' the input is used do set the filtering on the dialog box
    ' Returns Filename/Path OR Canceled
    Dim objfd As Object
    Dim vrtSelectedItem As Variant
    Dim strExtType As String
    Set objfd = Application.FileDialog(3)
  
    Select Case strFileExtension
        Case "xls", "xlsx"
            strExtType = "*.xls,*.xlsx"
        Case "txt", "asc", "csv"
            strExtType = "*.txt,*.acs,*.csv,*.prn"
        Case Else
            strExtType = "*.*"
    End Select
    With objfd
        .Title = "Please Select Your File"
        .AllowMultiSelect = bolAllowMultiSelect
        .Filters.Clear
        .Filters.Add "Files", strExtType, 1

        If .show = -1 Then

           For Each vrtSelectedItem In .SelectedItems
             'Return File Name and Path
               modImportExport_OpenFile = vrtSelectedItem  '<< Something needs to happen here to put selected files (1 or more) into an array to return
           Next vrtSelectedItem
                      
        Else
        'The user pressed Cancel.
            modImportExport_OpenFile = "Canceled"
        End If
        
    End With
    'Set the object variable to Nothing.
    Set objfd = Nothing
End Function

Open in new window

Avatar of Dale Fye
Dale Fye
Flag of United States of America image

You could insert items into your array at that entry point, or you could concatenate the individual file names to a string, using a separator like ";".  Then after the loop is done, you could simply use the Split( ) function to populate your array:

Dim myArray() as string

'insert other code here

myArray = Split(varFileNames, ";")

I prefer the latter because I don't have to dimension the array beforehand and check to see whether I have exceeded that value.
ASKER CERTIFIED SOLUTION
Avatar of Rey Obrero (Capricorn1)
Rey Obrero (Capricorn1)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of keschuster
keschuster

ASKER

so in my case where strFileList() = the array
Insert

           For Each vrtSelectedItem In .SelectedItems
               strFileList = Split(vrtSelectedItem, ";")  '<<< Insert this??
           Next vrtSelectedItem