2011-02-08 7 views
3

하나의 폴더에 여러 텍스트 파일이있어 매일 하나의 텍스트 파일을 추가합니다. 모든 텍스트 파일은 동일한 형식이며 파이프로 구분됩니다.여러 텍스트 파일을 하나의 Excel 시트로 가져올 수 있습니까?

여러 텍스트 파일의 데이터를 하나의 워크 시트로 자동으로 가져 오는 Excel 용 코드를 만들 수 있습니까?

폴더에서 모든 텍스트 파일을 가져올 일부 코드를 찾았습니다. 단, 모든 코드를 쉼표로 구분하여 변경 한 경우에만 해당합니다. 또한 폴더에 파일을 추가하면 업데이트 할 수 없습니다.

도움이 될 것입니다.

+0

이 먼저 가입하고 결과를 가져 오기? 탭으로 구분하려는 사용자의 경우 –

답변

1

디렉토리의 모든 파일을 순환하는 스크립트를 실행하고 모든 파일의 내용으로 구성된 새 파일을 새 줄로 작성하여 csv로 저장하는 것처럼 들릴 수 있습니다. 그런 다음 Excel에서 결과 CSV를 열고, 그 곳과 같은 스크립트를 저장하고 매일 그것을 실행할 수

import os 

basedir='c://your_root_dir' 
dest_csv="<path to wherever you want to save final csv>.csv" 
dest_list=[] 


for root, subs, files in os.walk(basedir): 
    for f in files: 
     thisfile=open(basedir+f) 
     contents=thisfile.readlines() 
     dest_list.append(contents) 

#all that would create a list containing the contents of all the files in the directory 
#now we'll write it as a csv 

f_csv=open(dest_csv,'w') 
for i in range(len(dest_list)): 
    f_csv.write(dest_list[i]) 
f_csv.close() 

: 같은 것을. 여기서는 특정 디렉토리의 각 파일에서 데이터를 가져오고 필요한 모든 파일이 하나의 디렉토리에 있다고 가정합니다.

4

일반적으로 파일을 처리하는 좋은 방법은 'FileSystemObject'입니다. VBA에서이 사용할 수 있도록하려면 당신은에 대한 참조를 추가해야합니다

(도구 \ 참조 메뉴를 선택 참조 대화에서 '마이크로 소프트 런타임 스크립팅'를 선택합니다.)

다음 코드 예제는 모두 읽습니다 파일을 폴더에 저장하고 한 번에 한 줄 씩 내용을 읽고 각 줄을 | 셀 A1에서 시작하여 라인 당 한 행씩 활성 시트에이 비트를 씁니다.

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:\YourDirectory\") 

    ' 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

은 "|"대신 vbTab를 사용합니다. – kunaguvarun

관련 문제