将多个文本文件导入Excel

问题描述:

我有大约600个文本文件。每个文件包含2列,并且是space delimited。有什么办法可以将它们全部导入到同一个Excel电子表格中?将多个文本文件导入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 

`

感谢您的帮助!

+0

可以将'Windo ws脚本运行时'参考下面提到的,或更改这2行:'Dim fso As FileSystemObject'和'Dim FileText As TextStream' to'... As Object',然后'Set fso = New FileSystemObject'设置为'Set fso =的CreateObject( “Scripting.FileSystemObject的”)'。同时进行下面@mkingston提到的更改。 – transistor1 2012-03-23 02:54:06

很可能您需要设置对Windows脚本宿主对象模型的引用。

为此,从Visual Basic编辑器中选择Tools/References,然后向下滚动以找到“Windows Script Host Object Model”。勾选此框然后按确定。现在尝试再次运行您的代码。

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

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 
+0

我应该怎么做?(我没有关于visual basic的知识) – dawnoflife 2012-03-23 01:56:05

+0

对不起!修订。 – mkingston 2012-03-23 02:00:25

+0

当我选择工具 - >参考。这个选项对我来说是无法访问的。我的意思是它没有突出显示/不可点击。我通过在工作表中按下“Alt + F11”后选择“添加新模块”选项来粘贴代码。谢谢您的帮助! – dawnoflife 2012-03-23 02:04:49