Discussion Locked

Get File Names

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
I am using FileSystem to access a folder and count the number of files in that folder. How do I get the names of the files in that folder into an array?

6 replies

by achp

From the MSDN:

Sub ShowFileList(folderspec)
Dim fs, f, f1, fc, s
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
s = s & f1.name
s= s & vbCrLf
Next
MsgBox s
End Sub

by gbworld

This example is VB, but it shows a simple method which will not require REDIMming an array with each loop.

Dim aryFiles As Variant
Dim objFSO As Scripting.FileSystemObject
Dim objFolder As Scripting.Folder
Dim objFile As Scripting.File
Dim strFiles As String

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Program Files")

For Each objFile In objFolder.Files

'* Load file names into comma delim str
strFiles = strFiles & objFile.Name & ","

Next objFile

'* Puts strFiles into the variant array
aryFiles = Split(strFiles, ",")

The other option is to continuously REDIM the array inside the for ... next loop. This is the easiest way if you intend on a multi-dimensional array.

Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

This discussion is closed to new replies.