2012-03-23 272 views
2

我有大約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

回答

3

很可能您需要設置對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