0

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

该代码将一系列文本文件导入到 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
4

2 回答 2

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)

这行得通吗?

于 2012-10-24T15:13:07.343 回答
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
于 2012-10-24T15:16:05.677 回答