엑셀 VBA 텍스트파일 읽어오기
반응형
엑셀 VBA에서 특정 폴더에 있는 모든 텍스트파일을 읽어올 수 있다.
아래와 같이 세 개의 텍스트파일이 있을 때, 각 텍스트 파일을 읽어서 엑셀 시트에 입력해보자.
엑셀에서 텍스트파일 순서대로 입력하려고 한다.
원하는 결과값은 아래와 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | '작성자 : prohannah2010 '특정 폴더 내에 존재하는 TEXT파일들을 읽어 Excel 내 쓰기 Public Sub run_gathering() Dim folder As String Dim folder_dri As String Dim folder_nm As String Dim intFree As Integer Dim txtfile_nm() As String Dim txtfile_cnt As Integer Dim text As Variant Dim i As Integer Dim j As Integer Dim x As Integer txtfile_cnt = 0 '임시변수 i = 0 j = 0 x = 0 '*********************************************************************************************** '1. 폴더 내 Text파일 목록 가져오기 (경로 설정에 주의하기) '*********************************************************************************************** folder_nm = "today_text" folder_dir = ThisWorkbook.Path & "\" & folder_nm & "\" '해당 엑셀파일(워크북)이 존재하는 디렉토리에 존재하는 'today_text'폴더에 위치한다는 의미이다. folder = Dir(folder_dir & "*.TXT", vbNormal) 'folder_dri 디렉토리 내에 *.txt형식의 파일을 순차적으로 호출한다. While folder <> "" i = i + 1 ReDim Preserve txtfile_nm(1 To i) txtfile_nm(i) = folder 'text파일명을 배열에 담는다. folder = Dir() Wend txtfile_cnt = i 'text파일 총 건수 '*********************************************************************************************** '2. Text파일 읽어오기(반복) '*********************************************************************************************** For j = 1 To txtfile_cnt intFree = FreeFile() 'Open txtfile_nm(j) Open folder_dir & txtfile_nm(j) For Input As #intFree If Err <> 0 Then MsgBox "Not found: " & txtfile_nm(j), vbCritical, "ERROR" Exit Sub End If x = Sheets("parsing_hst").Range("a1").End(xlDown).Row Do Until EOF(intFree) '한 줄 씩 읽는다 Line Input #intFree, Body_Line 'MsgBox Body_Line If Body_Line <> "" Then x = x + 1 text = Split(Body_Line, vbTab) Sheets("parsing_hst").Cells(x, 1).Value = text(0) Sheets("parsing_hst").Cells(x, 2).Value = text(1) Sheets("parsing_hst").Cells(x, 3).Value = text(2) End If Loop Close #intFree Next j End Sub | cs |
반응형
'Programming > VBA' 카테고리의 다른 글
엑셀 VBA ShellExcute 함수로 프로그램 실행/제어하기 (0) | 2017.03.08 |
---|