根据数据中的特定字符将多个文本文件导入Excel,并在导入时添加其他数据

时间:2012-12-10 16:04:54

标签: excel excel-vba import vba

我找到了将大量文本文件中的数据行导入Excel工作表的答案(由Chris Neilsen回答https://stackoverflow.com/a/4941605/1892030)。不过我还想做以下事情:

  1. 我要导入的有用数据前后有垃圾数据。我要导入的数据行都以asterix(*)开头。
  2. 数据以逗号分隔,在导入Excel时必须以这种方式解析。我可以通过编辑上面答案中的解析代码来改变。
  3. 在导入的每一行的末尾,我想添加一个额外的数据项,这是导入数据的文本文件的名称(仅限文件名,没有文件扩展名)。
  4. 克里斯的答案提到上面的工作真的很好,所以我想编辑代码以允许我在上面第1点和第3点的额外要求 - 但不知道如何。为了完整起见,我复制了下面前面的答案中的代码。非常感谢。

    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("C:\#test")
    
        ' 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 comma 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
    

1 个答案:

答案 0 :(得分:0)

我还没有为你完成这一切(我希望文件名需要整理以适应你想要的格式),但是请放下这些代码,它会让你开始......

    ' Read the file one line at a time
    Do While Not FileText.AtEndOfStream

        TextLine = FileText.ReadLine

        ' Process lines which don't begin with Asterisk (*)
        If Left(TextLine,1)<>"*" Then 

            ' This crudely appends the filename as if it were a column in the source file
            TextLine = TextLine + "," + file.Name

            ' Parse the line into comma 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)
        End If
    Loop