List Box

  • Thread starter Thread starter Dwight
  • Start date Start date
D

Dwight

Is there a way to display the file names from a folder in
a list box?

Thanks in advance!

Dwight
 
Dwight,

Yes. VBA is required. Instructions follow:

1) Set the "On Current" event in your form's property
sheet to "[Event Property]".

2) Click on the ellipsis button (...) to display your
form's "Form_Current" sub procedure in the VB editor.
Enter the below line in this procedure.

Me!YourListBox.RowSource = fnFileList("C:\")

(...and replace "YourListBox" with the actual name of your
list box. Also, replace "C:\" with your actual folder
path *including* the last "\".)

3) Add the below code to a new standard code module or to
an existing one.

Public Function fnFileList(strPath As String) As String
On Error GoTo Err_fnFileList

Dim strFileList As String
Dim strNextFile As String

strNextFile = Dir(strPath & "*.*") ' Retrieve the
first entry.
Do While strNextFile <> "" ' Start the loop.
' Ignore the current directory and the
encompassing directory.
If strNextFile <> "." And strNextFile <> ".." Then
' Use bitwise comparison to make sure
strNextFile is not a directory.
If (GetAttr(strPath & strNextFile) And
vbDirectory) <> vbDirectory Then
fnFileList = fnFileList & strNextFile & ";"
End If
End If
strNextFile = Dir ' Get next entry.
Loop

Exit_fnFileList:
Exit Function

Err_fnFileList:
If Err.Number <> 2501 Then
MsgBox "Error #: " & vbTab & vbTab & Err.Number &
vbCrLf _
& "Description: " & vbTab & Err.Description
End If
Resume Exit_fnFileList

End Function

4) Compile your updated code via Debug/Compile.

5) Open your form. The list box should be populated with
all files (having no attributes) contained within the
specified folder. The above function can be tweaked to
filter for a specific file type, like "*.txt" or for files
having a "vbReadOnly" attribute, etc. This should be
enough to get you started.
 
Back
Top