将文本拆分为行excel

时间:2012-11-29 13:54:27

标签: excel file vba excel-vba

我有一个VBA代码,我将txt文件导入一个单元格。 这是代码(它并不重要):

Sub ReadFile()
     ' Requires a reference to Microsoft Scripting Runtime (Tools > References)
    Dim FSO As FileSystemObject
    Dim FSOFile As File
    Dim FSOStream As TextStream

    Dim Rand
    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")

   Set FSO = New FileSystemObject
   Set FSOFile = FSO.GetFile("C:\Users\sdagfsgedg\Desktop\20121122.log")
   Set FSOStream = FSOFile.OpenAsTextStream(ForReading, TristateUseDefault)
   Rand = 1
   Do While Not FSOStream.AtEndOfStream
        ws.Cells(Rand, 1).Value = FSOStream.ReadAll
   Loop
End Sub

文本文件20121122.log有大约20,000行,这些行都在一个单元格中导入。如何将该单元格拆分为20.000个单元格(如果日志有20.000行)。我不希望逐行读取文本文件...我想要全部读取它(它的速度更快)然后将每一行拆分到一个单独的行上。

稍后编辑: 或者,如果有另一个解决方案来读取日志文件并将文本粘贴为行(不是像我现在那样在一个单元格中的所有内容)

1 个答案:

答案 0 :(得分:2)

//代码未经过测试

Sub ReadFile()
  Dim FSO As FileSystemObject
  Dim FSOFile As File
  Dim FSOStream As TextStream

  Dim Rand
  Dim row
  Dim ws As Worksheet
  Set ws = Worksheets("Sheet1")

  Set FSO = New FileSystemObject
  Set FSOFile = FSO.GetFile("C:\Users\sdagfsgedg\Desktop\20121122.log")
  Set FSOStream = FSOFile.OpenAsTextStream(ForReading, TristateUseDefault)
  Rand = 1
  Dim content As String
  Dim lines As Variant
  Dim intIndex As Integer

  content = FSOStream.ReadAll
  lines = split(content, Chr(10))

  For intIndex = LBound(lines) To UBound(lines)
    ws.Cells(Rand, 1).Value = lines(intIndex)
    Rand = Rand + 1
  Next

End Sub