将多个文本文件导入Excel

时间:2012-03-23 01:50:48

标签: excel vba

我有大约600个文本文件。每个文件包含2列,space delimited。有什么方法可以将所有这些导入到同一个Excel电子表格中吗?

我看到一篇关于此的帖子并使用了以下脚本,但这对我不起作用。它给了我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

`

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

您很可能需要设置对Windows Scripting Host Object Model的引用。

要执行此操作,请从Visual Basic编辑器中选择“工具/引用”,然后向下滚动以查找“Windows脚本宿主对象模型”。勾选此框,然后按确定。现在尝试再次运行您的代码。

此外,我注意到你提到你的数据被分成两列并以空格分隔。您需要在以下行中替换分隔符:

Items = Split(TextLine, "|")

有了这个:

Items = Split(TextLine, " ")

最后,你可以稍微更好一点:

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

有了这个:

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