View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
Conan Kelly Conan Kelly is offline
external usenet poster
 
Posts: 98
Default Looping through folders and using the first file in each folder

Hello all,

How do I loop through folders and get the first file from each folder?

I have code that will loop through a set of folders, gets the column labels out of the first file in each folder and lists them in
the current workbook. The problem is that I'm getting the first file in each folder by using it's file name. If the files in each
folder are named the same, then this won't work correctly.

Isn't there a way to get the first file without having to use the file name?

Here is the code:


Sub List_FileName_ColumnHeaders()
Dim fso As New FileSystemObject
Dim fsoFolder As Folder
Dim fsoSubFolder As Folder
Dim fsoFile As File

Dim pstrCol1 As String
...
Dim pstrCol16 As String

pstrCol1 = ""
...
pstrCol16 = ""

Set fsoFolder = fso.GetFolder("X:\Some Folder\Data Files")

For Each fsoSubFolder In fsoFolder.SubFolders


Set fsoFile = fsoSubFolder.Files("2003-08_Aug 2003.csv")
'***This is where I'm having problems. ***'
'***"Set fsoFile = fsoSubFolder.Files(1)" does not work ***'
'***When I use the "...fsoSubFolder.Files(1)", I get an ***'
'***"Invalid procedure call or argument".


ActiveCell = fsoFile.Name

Open fsoFile For Input As #1

Input #1, pstrCol1, ... , pstrCol16

Cells(ActiveCell.Row, ActiveCell.Column + 1) = pstrCol1
...
Cells(ActiveCell.Row, ActiveCell.Column + 16) = pstrCol16

Close #1

Cells(ActiveCell.Row + 1, ActiveCell.Column).Select

Next fsoSubFolder



End Sub



--
Thanks for any help anyone can provide,

Conan Kelly