dawnoflife
dawnoflife

Reputation: 1652

Importing multiple text files to Excel

I have about 600 text files. Each file contains 2 columns and is space delimited. Is there any way I can import all of them to the same excel spreadsheet?

I saw a post about this and used the following script but that didn't work for me. It gived me User-defined type not defined

Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range

' Get a FileSystem object
Set fso = New FileSystemObject

' get the directory you want
Set folder = fso.GetFolder("D:\mypath\")

' set the starting point to write the data to
Set cl = ActiveSheet.Cells(1, 1)

' Loop thru all files in the folder
For Each file In folder.Files
    ' Open the file
    Set FileText = file.OpenAsTextStream(ForReading)

    ' Read the file one line at a time
    Do While Not FileText.AtEndOfStream
        TextLine = FileText.ReadLine

        ' Parse the line into | delimited pieces
        Items = Split(TextLine, "|")

        ' Put data on one row in active sheet
        For i = 0 To UBound(Items)
            cl.Offset(0, i).Value = Items(i)
        Next

        ' Move to next row
        Set cl = cl.Offset(1, 0)
    Loop

    ' Clean up
    FileText.Close
Next file

Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing

End Sub

`

Thanks for the help!

Upvotes: 2

Views: 5804

Answers (1)

mkingston
mkingston

Reputation: 2718

Most likely you need to set a reference to the Windows Scripting Host Object Model.

To do this, from the Visual Basic Editor choose Tools/References, then scroll down to find "Windows Script Host Object Model". Tick this box then press OK. Now try to run your code again.

Additionally, I notice you mention that your data is split into two columns and space-delimited. You'll need to replace the delimiter on the following line:

Items = Split(TextLine, "|")

With this:

Items = Split(TextLine, " ")

Finally, you'd be slightly better off replacing this:

For i = 0 To UBound(Items)
  cl.Offset(0, i).Value = Items(i)
Next

With this:

cl.Resize(1,UBound(Items)-LBound(Items)+1).value = Items

Upvotes: 3

Related Questions