extract data from multiple text files in a folder into excel worksheet

后端 未结 2 1506
半阙折子戏
半阙折子戏 2020-12-22 09:48

I have multiple \"datasheet\" text files that are used with a program at work and need to harvest values from them and combine it all into a spreadsheet.

The text fi

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 10:30

    Thanks for the help, here is the solution I came up with for this specific problem

    Sub OpenFiles()
    
    Dim MyFolder As String
    Dim MyFile As String
    
    MyFolder = "[directory of files]"
    MyFile = Dir(MyFolder & "\*.txt") 
    Dim filename As String
    Dim currentrow As Integer: currentrow = 2
    
    
        Do While Myfile <> ""  'This will go through all files in the directory, "Dir() returns an empty string at the end of the list
        'For i = 1 To 500   'this was my debug loop to only go through the first 500 files at first
    
            filename = MyFolder & "\" & MyFile  'concatinates directory and filename
    
            Open filename For Input As #1 
    
            Do Until EOF(1)  'reads the file Line by line
                Line Input #1, textline  
                'Text = Text & textline
                If textline = "" Then  'error handler, if line was empty, ignore
                Else
                    Dim splitline() As String
                    splitline() = Split(textline, "=", -1, vbTextCompare) 
    'because of how my specific text was formatted, this splits the line into 2 strings.  The Tag is in the first element, the data in the second
    
                    If IsError(splitline(0)) Then
                        splitline(0) = ""
                    End If
    
                    Select Case Trim(splitline(0)) 'removes whitespace
                    Case "DescText"
                        currentrow = currentrow + 1 
    'files that didn't have a description row, resulted in empty rows in the spreadsheet.
                        ActiveSheet.Range("A" & currentrow).Cells(1, 1).Value = splitline(1)
    
                    Case "Revision"
                        ActiveSheet.Range("B" & currentrow).Cells(1, 1).Value = splitline(1)
                     Case "ProdCode"
                        ActiveSheet.Range("C" & currentrow).Cells(1, 1).Value = splitline(1)
                     Case "ProdType"
                        ActiveSheet.Range("D" & currentrow).Cells(1, 1).Value = splitline(1)
    
                    '...etc. etc... so on for each "tag"
                    End Select
                End If
            Loop
    
            Close #1
    
    
            MyFile = Dir()  'reads filename of next file in directory
            'currentrow = currentrow + 1
    
    
        'Next i
        Loop
    
    End Sub
    

提交回复
热议问题