programing

VBA에서 텍스트 파일을 한 줄씩 읽고 구문 분석

cafebook 2023. 4. 28. 21:31
반응형

VBA에서 텍스트 파일을 한 줄씩 읽고 구문 분석

나는 VBA를 사용하여 텍스트 문서를 구문 분석하고 텍스트 파일에 지정된 경로를 반환하려고 합니다.예를 들어 텍스트 파일은 다음과 같습니다.

*Blah blah instructions
*Blah blah instructions on line 2
G:\\Folder\...\data.xls
D:\\AnotherFolder\...\moredata.xls

나는 VBA가 한 번에 한 줄씩 로드하기를 원하며, 만약 그것이 시작된다면,*그런 다음 다음 다음 줄로 이동합니다(댓글이 표시되는 줄과 유사).파일 경로가 있는 행의 경우 셀에 해당 경로를 기록합니다.A2첫 번째 길을 위해,B2다음 등을 위하여.

제가 대답하고 싶었던 주요 사항은 다음과 같습니다.

  1. VBA를 사용하여 텍스트 파일을 읽는 가장 좋고 간단한 방법은 무엇입니까?
  2. 어떻게 하면 한 줄 한 줄 할 수 있을까요?

텍스트 파일의 가장 기본적인 읽기를 위해,open

예:

Dim FileNum As Integer
Dim DataLine As String

FileNum = FreeFile()
Open "Filename" For Input As #FileNum

While Not EOF(FileNum)
    Line Input #FileNum, DataLine ' read in data 1 line at a time
    ' decide what to do with dataline, 
    ' depending on what processing you need to do for each case
Wend

#작성자 노트 - 추가를 중지하십시오.close #FileNum그것은 댓글에서 다루어졌고, 이 답변의 개선으로 필요하지 않습니다.

파일을 읽는 가장 쉬운 방법은 TxtStream이 있는 FileSystemObject입니다.

Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)

그럼 이걸로.txtStream객체는 인텔리센스가 선택하는 모든 종류의 도구를 가지고 있습니다(사용하는 것과 달리).FreeFile()방법) 그래서 추측이 적습니다.또한 FreeFile(자유 파일)을 할당할 필요가 없으며 할당한 이후에도 실제로 무료이기를 바랍니다.

다음과 같은 파일을 읽을 수 있습니다.

Do While Not txtStream.AtEndOfStream
    txtStream.ReadLine
Loop
txtStream.Close

참고: 이를 위해서는 Microsoft 스크립팅 런타임에 대한 참조가 필요합니다.

완전성을 위해; 메모리에 로드된 데이터 작업;

dim hf As integer: hf = freefile
dim lines() as string, i as long

open "c:\bla\bla.bla" for input as #hf
    lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf

for i = 0 to ubound(lines)
    debug.? "Line"; i; "="; lines(i)
next

당신은 이 코드를 사용하여 텍스트 파일에서 한 줄씩 읽을 수 있고 첫 번째 문자가 "*"인지 확인할 수도 있습니다. 그런 다음 그것을 남길 수 있습니다.

Public Sub Test()

    Dim ReadData as String

    Open "C:\satheesh\myfile\file.txt" For Input As #1

    Do Until EOF(1) 
       Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
    If Not Left(ReadData, 1) = "*" then
       '' you can write the variable ReadData into the database or file
    End If 

    Loop

    Close #1

End Sub

아래는 텍스트 파일 읽기부터 엑셀 파일까지 제 코드입니다.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

언급URL : https://stackoverflow.com/questions/11528694/read-parse-text-file-line-by-line-in-vba

반응형