2012-03-23 2 views
2

약 600 개의 텍스트 파일이 있습니다. 각 파일에는 두 개의 열이 있으며 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 
도움을

`

감사 gived!

+0

ws Scripting Runtime' 레퍼런스를 수정하거나이 두 줄을 변경하십시오 :'Dim fso As FileSystemObject' 그리고'Dim FileText As TextStream'을'... As Object'로 변경 한 다음'Set fso = New FileSystemObject'를'Set fso = CreateObject ("Scripting.FileSystemObject")'입니다. 또한 아래 @mkingston에서 언급 한 변경 사항을 적용하십시오. – transistor1

답변

3

대부분 Windows Scripting Host Object Model에 대한 참조를 설정해야합니다.

이렇게하려면 Visual Basic Editor에서 Tools/References를 선택한 다음 아래로 스크롤하여 "Windows Script Host Object Model"을 찾으십시오. 이 상자를 선택한 다음 확인을 누릅니다. 이제 코드를 다시 실행하십시오.

또한 데이터가 두 개의 열로 분리되고 공백으로 구분된다는 사실을 알게되었습니다.

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

으로 :

Items = Split(TextLine, " ") 

마지막으로, 당신이 교체 떨어져 약간 더 나은 것 :이

Items = Split(TextLine, "|") 

다음과 같은 줄에 구분 기호를 교체해야합니다 이 :

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

그리고 어떻게해야합니까? (시각적 기본 지식이 없습니다) – dawnoflife

+0

죄송합니다! 수정 됨. – mkingston

+0

도구 -> 참조를 선택할 때. 이 옵션은 나에게 접근 할 수 없다. 강조 표시되어 있지 않거나 클릭 할 수없는 <올바른 용어를 여기에 삽입하십시오.> 워크 시트에서'Alt + F11'을 누른 후'add new module' 옵션을 선택하여 코드를 붙여 넣었습니다. 도와 주셔서 감사합니다! – dawnoflife

관련 문제