在VBA中打开多个文本文件作为数组

时间:2014-01-22 22:14:00

标签: excel-vba vba excel

我一直在使用这篇文章中的代码导入几个txt文件。我想将每个值或字符串放在一个单元格中作为数组。但是所有这些都放在一行中,所以我有一列和几行。

代码是:

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("G:\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 | delimited pieces
        Items = Split(TextLine, " ", 1)

        ' 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

Plz帮帮我.. 提前谢谢

1 个答案:

答案 0 :(得分:0)

在这里,您将拆分该行并将每个令牌放在不同的列中。如果您不想拆分它们,请删除这些行。

' Parse the line into | delimited pieces
Items = Split(TextLine, " ", 1)

' Put data on one row in active sheet
For i = 0 To UBound(Items)
        cl.Offset(0, i).Value = Items(i)
Next

然后只需添加回cl.Value = TextLine