Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looping through files in a folder... 1

Status
Not open for further replies.

NigelHarper

Technical User
Apr 3, 2001
13
0
0
GB
I have a folder that contains various file types. From Excel I want to be able to loop through the folder opening only txt files and importing their contents to a workbook. How do I do the looping through the folder looking for only the txt files bit?
 
IN the VBA editor, go to Tools>References and add a reference to Microsoft Scripting Runtime, then add this code wherever you need it

Dim fso As FileSystemObject
Dim fld As Folder
Dim fil As File

Set fso = New FileSystemObject
Set fld = fso.GetFolder("C:\MyFolder")

For Each fil In fld.Files
If Right$(fil.Name, 4) = ".txt" Then
'do whatever
End If
Next fil

Hope that's what you're looking for
 
Alternatively you can use:

MySearch = [MyPath] & "\*.txt"
Found = Dir(MySearch)
Do While Found <> &quot;&quot;
Workbooks.open filename:=found
Found = Dir
Loop
Store300

Store300@ftnetwork.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top