0

我有一个 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 行)。我不想逐行阅读文本文件...我想全部阅读(这样更快)然后将每一行拆分为单独的行。

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

4

1 回答 1

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
于 2012-11-29T14:21:47.637 回答