I've created a Userform
on excel 2010 VBA (7.0) which will transfer a file selected by the user via the .GetOpenFileName
property. The file paths of the selected files are then inserted into the ListBox
My issue is at the moment I am trying to use a MultiSelect
, however when I give .GetOpenFileName
the Multiselect
property to send the file paths to my ListBox
(which is Multiline enabled) I am presented with a type mismatch error shown for the GetOpenFileName
line of code. Code sample is below:
Private Sub CommandButton1_Click ()
Dim strFilePath As String
StrFilePath = Application.GetOpenFilename (,,,, MultiSelect:= True)
If strFilePath = "False" Then Exit Sub
FilesFrom.Value = strFilePath
End Sub
FilesFrom being the listbox I want the filepaths to go into. I have the code working to allow the user to select a single file and transfer that but it won't allow me to populate this listbox with multiple filepaths.
Any ideas on how I can allow the user to select multiple files and insert the file paths into the listbox named FilesFrom?
The problem is that the MultiSelect
returns an Array
.
The code below should be exactly what you want. It caters for Multi or Single Selection.
Private Sub CommandButton1_Click()
'GetOpenFile MultiSelect will return an Array if more than one is selected
Dim FilePathArray As Variant
FilePathArray = Application.GetOpenFilename(, , , , MultiSelect:=True)
If IsArray(FilePathArray) Then
Dim ArraySize As Long
ArraySize = UBound(FilePathArray, 1) - LBound(FilePathArray, 1) + 1
Dim ArrayPosition As Long
For ArrayPosition = 1 To ArraySize
If Not FilePathArray(ArrayPosition) = Empty Then
'Replace "UserForm1" with the name of your Userform
UserForm1.FilesFrom.AddItem (FilePathArray(ArrayPosition))
End If
Next ArrayPosition
ElseIf FilePathArray <> False Then
'Replace "UserForm1" with the name of your Userform
UserForm1.FilesFrom.AddItem (FilePathArray)
End If
End Sub