opening multiple files from within a macro
Hi, Tom:
In my experience, if, between calls to Dir$, you make any changes to the
directory, like saving a file, it gets "mixed up" and may skip a file or
process one twice. This may not be a problem if you are only opening the file,
then closing it without resaving.
To avoid any problems, I usually use a first Do/Loop to get all of the file
names into an array, then a 2nd For/Next loop to retrieve the names from the
array and process the files.
I do this often enough that I wrote a sub to get the file names, so my code
would look like this:
Dim sPath as String
Dim sName as String
Dim bk as Workbook
Dim FileList() As String
Dim i As Long
Dim n As Long
sPath = "C:\Myfolder\"
sName = "*.xls"
n = GetFileList(sPath & sName, FileList())
For i = 1 to n 'NB: loop won't execute if n = 0
set bk = workbooks.open(sPath & FileList(i))
'process bk
Next i
~~~~~~~~~~~~~~~~~~~~~
Function GetFileList(Pattern As String, FileNames() As String) As Long
Dim f As String
Dim n As Integer
n = 0
Erase FileNames()
f = Dir$(Pattern)
Do While Len(f)
n = n + 1
ReDim Preserve FileNames(1 To n) As String
FileNames(n) = f
f = Dir$()
Loop
GetFileList = n
End Function 'GetFileList
On Mon, 30 Aug 2004 16:06:26 -0400, "Tom Ogilvy" wrote:
Dim sPath as String, sName as String
Dim bk as Workbook
sPath = "C:\Myfolder\"
sName = Dir(sPath & "*.xls")
do while sName < ""
set bk = workbooks.open(sPath & sName)
. . . process bk
bk.close Savechanges:=False ' or true
sName = Dir
Loop
|