2013-04-30 128 views
2

所以这个Excel宏的作品,从一个特定的文件夹读取多个txt文件,并插入在第一Excel工作表中的所有行很大。我想编辑此代码,以便让宏跳过每个txt文件的第一行。我怎么可以阅读TXT文件中的行,但是从第二行开始,跳过第一行?

任何人都可以帮忙吗?

Sub test1() 
    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("C:\Users\Desktop\TXT") 

    ' 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, vbTab) 

      ' Put data on one row in active sheet 
      cl.Value = file.Name 
      ' Put data on one row in active sheet 
      For i = 0 To UBound(Items) 
       cl.Offset(0, i + 1).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 
+1

你为什么?通过在文本文件中的每一行循环这会减慢你的代码通过阵列阅读一气呵成在文件中的数组,然后循环,方法,你可以轻松地跳过任何你想要的行; [这](HTTP。: //stackoverflow.com/questions/16286769/how-to-do-searching-after-a-particular-line-in-text-file-from-excel) – 2013-04-30 17:24:33

回答

2

选项1阅读第一线的前期

您启动之前做While循环中加入这一行:

If Not FileText.AtEndOfStream Then TextLine = FileText.ReadLine 

这样,你会读到的第一行(如果有的话)并且您的Do While循环只会读取后续文件

选项2删除第一行excel之后

另一种解决方案可能是在脚本完成导入所有文件后,在Excel中删除第一行。

您可能必须具体到哪个列适用于作为我不确定如果活动导入是唯一一个(否则你将消除不应该有在所有被删除以前导入的值!

+0

完美!谢谢...去与选项1,当然... – 2013-04-30 16:22:33