将文本文件导入Excel - 每个文件中的行放在同一行的不同列中

时间:2012-10-24 15:02:34

标签: excel excel-vba vba

我在这个网站上找到了这个代码但是我无法根据自己的需要调整它,尽管我认为它必须是一个非常快速的解决方案。

代码将一系列文本文件导入excel。打开一个文件,该文件的第一行放在A1中,第二行放在A2中,依此类推。打开新文件时,文本将放在A列的下一个可用单元格中(所有文件都读入A列)。

我想稍作修改。我想要A1中的第一行文件1,B1中的第二行等等(即文件1中的所有行都保存在第1行中)。然后,文件2中的行放在第2行,文件3放在第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("D:\YourDirectory\")  

    ' 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 | 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

2 个答案:

答案 0 :(得分:0)

我认为将所有对行和列的引用相互替换就足够了。尝试:

  1. cl.Offset(0, i).Value = Items(i)替换为cl.Offset(i, 0).Value = Items(i)

  2. Set cl = cl.Offset(1, 0)替换为Set cl = cl.Offset(0, 1)

  3. 这样做可以吗?

答案 1 :(得分:0)

叶氏。满容易。只需要调整列和行的偏移方式,并且不需要在读取时划分每一行。

请参阅下面的调整后代码:

Sub ReadFilesIntoActiveSheet()

Dim fso As FileSystemObject
Dim folder As folder, file As file, FileText As TextStream
Dim TextLine As String, Items() As String
Dim i As Long, cl As Range

' Get a FileSystem object
Set fso = New FileSystemObject

' get the directory you want
Set folder = fso.GetFolder("D:\YourDirectory\")

Dim x As Long
x = 1 'to offset rows for each file

' Loop thru all files in the folder
For Each file In folder.Files

    ' set the starting point to write the data to
    Set cl = ActiveSheet.Cells(x, 1)

    ' Open the file
    Set FileText = file.OpenAsTextStream(ForReading)

    Dim i As Long
    i = 0 'to offset columsn for each line
    ' Read the file one line at a time
    Do While Not FileText.AtEndOfStream

        TextLine = FileText.ReadLine 'read line

        cl.Offset(, i).Value = TextLine 'fill cell

        i = i + 1
    Loop

    ' Clean up
    FileText.Close

    x = x + 1

Next file

Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing

End Sub