How to Clear Items from Listbox




How to Clear Items from Listbox

In this How To, I will show how to clear items from a listbox. I will use the form that I created for How to Add Items from File Dialog to Listbox and add a Clear List button.

Step 1. Add Clear List button

  • Under the Design Menu, click a Command button icon then place it below the Add File button
  • Rename a button caption as Clear List
  • Name a button under the Other tab of Property Sheet as cmdClearList

  • Click Event tab of Property Sheet
  • Select [Event Procedure] on On Click event
  • Click three dots() at the end of [Event Procedure] to open the VB application

Step 2. Add VBA to Clear List button

  • Enter VBA code below under the On Click Event Procedure
Private Sub cmdClearList_Click()
Dim i As Integer
For i = lstFileLocation.ListCount - 1 To 0 Step -1
    lstFileLocation.RemoveItem (i)
Next i
Me.txtFile = Null
End Sub

The VBA code above will remove the file path from File textbox and all file paths from the listbox.

Step 3. Add Clear List button

  • Save and close the form design view
  • Open form 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.

  • Click Clear List button

The file paths on both File box and on the listbox are removed same time.