2013-04-30 96 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

相關問題