Extract Data from Text File into Excel

£可爱£侵袭症+ 提交于 2021-01-29 10:56:44

问题


I am new to VBA so getting my task done is quite a struggle. Been reading and trying codes from different threads for a few days now to no success. So I am hoping someone could assist me.

I have multiple text files that I need to extract data from. But I only need certain data such as DATE-TIME to be placed in the 1st column and CARD NUMBER in the 2nd column. Got codes from this thread >> Extract a single line of data from numerous text files and import into Excel but my output only shows the first data from the file. Please see the attached files below.

sample text

Output

Desired Output

Here's what I have:

Sub ExtractData()
Dim filename As String, nextrow As Long, MyFolder As String
Dim MyFile As String, text As String, textline As String, filedate As String
Dim filenum As Integer

MyFolder = "C:\directory\"
MyFile = Dir(MyFolder & "*.txt")

Do While MyFile <> ""
    Open (MyFolder & MyFile) For Input As #1
    Do Until EOF(1)
        Line Input #1, textline
        text = text & textline

    Loop
    Close #1
    MyFile = Dir()
    Debug.Print text
    filedate = InStr(text, "DATE-TIME")
    nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
    ActiveSheet.Cells(nextrow, "A").value = Mid(text, filedate + 16, 17)

    filenum = InStr(text, "CARD NUMBER")
    nextrow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row + 1
    ActiveSheet.Cells(nextrow, "B").value = Mid(text, filenum + 16, 10)
    text = ""  
Loop
End Sub

回答1:


I modify the code for you, it can work:

Sub ExtractData()
Dim filename As String, nextrow As Long, MyFolder As String
Dim MyFile As String, text As String, textline As String, filedate As String
Dim filenum As Integer
dim idx%

MyFolder = "C:\directory\"
MyFile = Dir(MyFolder & "*.txt")

nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

Do While MyFile <> ""

    Open (MyFolder & MyFile) For Input As #1

    'nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

    Do Until EOF(1)
        Line Input #1, textline 'read a line

        idx = InStr(textline, "DATE-TIME") ' if has date, set it but not move to the next ROW
        if idx > 0 then 
            ActiveSheet.Cells(nextrow, "A").value = Mid(textline, idx + 16)
        end if

        idx = InStr(textline, "CARD NUMBER")
        if idx > 0 then
            ActiveSheet.Cells(nextrow, "B").value = Mid(textline, filenum + 16)

            nextrow = nextrow + 1 'now move to next row

        end if

    Loop
    Close #1
    MyFile = Dir()

Loop
End Sub


来源:https://stackoverflow.com/questions/51635537/extract-data-from-text-file-into-excel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!