View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
JP[_4_] JP[_4_] is offline
external usenet poster
 
Posts: 897
Default Automatically input file names from a directory to Excel sheet?

Shouldn't you check if myFile is empty *before* starting the loop, in
case the folder is empty? Then you wouldn't need to check myFile
inside the loop, which could potentially be looped dozens or hundreds
of times.

myFile = Dir(myFolder & "*.xls*")

Do While myFile < ""
lRow = lRow + 1
aWS.Cells(lRow, 1) = myFile
myFile = Dir
Loop

--JP

On Sep 28, 4:32*pm, Barb Reinhardt
wrote:
You could do something like this

Option Explicit

Sub Test()

Dim myFolder As String
Dim myFile As String
Dim lRow As Long
Dim aWS As Excel.Worksheet

Set aWS = Workbooks.Add.ActiveSheet
aWS.Name = "List"

lRow = 1
aWS.Cells(1, 1) = "FileName"

myFolder = "C:\Documents and Settings\barbara.reinhardt\Desktop\" * '<~~ *
change this to whatever you want it to be

If Right(myFolder, 1) < "\" Then
* *myFolder = myFolder & "\"
End If

myFile = Dir(myFolder & "*.xls*")

Do
* *If myFile < "" Then
* * * lRow = lRow + 1
* * * aWS.Cells(lRow, 1) = myFile
* *End If
* *myFile = Dir

Loop While myFile < ""
End Sub