ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   For loop for each file in a folder? (https://www.excelbanter.com/excel-programming/316328-loop-each-file-folder.html)

Kieran1028[_6_]

For loop for each file in a folder?
 

I've got a macro that imports a .txt file and moves the data around, an
copies some things here and there... I need to run this macro on abou
40 different .txt files in a folder. Is there a way to write
For-loop that will run the macro on EACH text file in a give
directory?

Thanks,
Kiera

--
Kieran102
-----------------------------------------------------------------------
Kieran1028's Profile: http://www.excelforum.com/member.php...fo&userid=1567
View this thread: http://www.excelforum.com/showthread.php?threadid=27701


Tom Ogilvy

For loop for each file in a folder?
 
sFile = dir("C:\Myfolder\*.txt")
do while sFile < ""
bk =Workbooks.Open("C:\MyFolder\" & sFile)
. . .
bk.Close SaveChanges:=false
sFile = Dir()
Loop

If you are going to save the changed files, you might want to use the above
construct to build an array of file names, then process that array rather
than process the files immediately. There is a KB article that says that
changing the directory in the middle of a DIR loop can cause problems
although I have never encountered any.

--
Regards,
Tom Ogilvy


"Kieran1028" wrote in message
...

I've got a macro that imports a .txt file and moves the data around, and
copies some things here and there... I need to run this macro on about
40 different .txt files in a folder. Is there a way to write a
For-loop that will run the macro on EACH text file in a given
directory?

Thanks,
Kieran


--
Kieran1028
------------------------------------------------------------------------
Kieran1028's Profile:

http://www.excelforum.com/member.php...o&userid=15678
View this thread: http://www.excelforum.com/showthread...hreadid=277010





All times are GMT +1. The time now is 07:27 AM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com