How to Add Items from File Dialog to Listbox




How to Add Items from File Dialog to Listbox

How to create a Listbox is similar to creating a Combobox. You can see more details on Working with Combo box How To on my website.  In this How To, I will show how to add a file path or location from a file dialog into a list box.

Step 1. Add List Box to Form

  • Under the Design Menu, click a List Box icon then place it on top of form
  • It will open the List Box Wizard below

  • Click Cancel button to cancel List Box wizard

  • Rename list label as File Location:
  • Click Data tab of the Property Sheet
  •  Select Value List for the Row Source Type

  • Name a list box as lstFileLocation

Step 2. Add Textbox to Form

  • Click on Textbox icon and drag it to form

  • Select Textbox and name it as txtFile
  • Rename text label as File:




Step 3. Add Command Button to Form

  • Click on Command button icon

  • Place it next to the textbox File
  • Select Command button
  • Rename a button label as Add File:

  • Open the Property Sheet of Add File button
  • Click Event tab
  • Select [Event Procedure] of On Click event
  • Click three dots() at the end of [Event Procedure]
  • Enter VBA code below:
Private Sub Command2_Click()
Const msoFileDialogFilePicker As Long = 3
Dim FD As Object
Dim file As Variant
Dim SelectFile As String
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
    .AllowMultiSelect = False
    .Title = " Please select file"
    If .Show = True Then
        Selectfile = .selectedItems(1)
        Me.txtFile = Selectfile
        Me.lstFileLocation.AddItem (Selectfile)
    Else
        Exit Sub
    End If
    Set FD = Nothing
End With
End Sub

 

Step 4. Adding File Path to Listbox

  • Save and close the form design view
  • Open form Add Items from File Dialog to Listbox again
  • Click on Add File button
  • Select file that you want to show on the list box

The selected file from dialog will be displayed in the File textbox and in the listbox. When you add more files, they will be added into the listbox until you clear the listbox. More details on clearing the listbox here.