我在这个网站上找到了这段代码,但我无法根据自己的需要调整它,尽管我认为它必须是一个非常快速的修复。
该代码将一系列文本文件导入到 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