2012-10-26 34 views
0

我有許多文本文件需要導入到excel中。我想讓我的宏打開一個文件,當它遇到單詞「PRICE」時,它將該行放置在A1中。之後的每一行將被放置在b1,c1等。當再次找到PRICE這個詞時,會開始一個新行,並將該行放在a2中,然後是b2,c2中的行。我想我應該使用Instr。下面的代碼似乎將帶有PRiCE的行放在新行中,但文本文件中的以下行似乎不遵循。我想我只需要在DO內進行小調整,而不是循環。任何幫助都會很棒!將文本文件導入到excel中 - 每遇到一個單詞時都會啓動一個新行

x = 1 'to offset rows for each file 

' Loop thru all files in the folder 
For Each file In folder.Files 

' set the starting point to write the data to 
Set cl = ActiveSheet.Cells(x, 1) 

' Open the file 
Set FileText = file.OpenAsTextStream(ForReading) 



i = 0 'to offset columsn for each line 
' Read the file one line at a time 
Do While Not FileText.AtEndOfStream 

    TextLine = FileText.ReadLine 'read line 

    If InStr(TextLine, "FINEX") > 0 Then 'find text 

    x = x + 1 
    Set cl = ActiveSheet.Cells(x, 1) 
    cl.Offset(, 0).Value = TextLine 
    'i = i + 1 
    'cl.Value = TextLine 

    'MsgBox ("yes") 
    Else 
    cl.Offset(, i).Value = TextLine 'fill cell 
    i = i + 1 
    End If 
Loop 

' Clean up 
FileText.Close 

x = x + 1 

Next file 
+0

你在你的解釋說'Price',但'FINEX'在你的代碼...這是它? –

回答

1

因爲我昨天幫你這個代碼,碰巧看到,我想我會刺傷採取:

看看下面的代碼獲取它。如果沒有,讓我知道,我可以調整它:

x = 1 'to offset rows for each file and at price 

' Loop thru all files in the folder 
For Each file In folder.Files 

    ' set the starting point to write the data to 
    Set cl = ActiveSheet.Cells(x, 1) 

    ' Open the file 
    Set FileText = file.OpenAsTextStream(ForReading) 

    i = 1 'to offset columsn for each line 

    ' Read the file one line at a time 
    Do While Not FileText.AtEndOfStream 

     TextLine = FileText.ReadLine 'read line 

     If InStr(TextLine, "PRICE") > 0 Then 'find text 

      cl.Offset(x - 1, 0).Value = TextLine 
      x = x + 1 

     Else 

      cl.Offset(x - 1, i).Value = TextLine 'fill cell 
      i = i + 1 

     End If 

    Loop 

Next 
+0

謝謝斯科特。當「價格」這個詞出現時,這開始了新的一輪。不幸的是,原始文本文件中PRICE行後面的行沒有放在列b,c,d等中。相反,如果它們在原始文本文件的第26行中,則放在列Z中。我使用了舊的宏,我不得不刪除不需要的空白單元格,但仍然剩下幾個。刪除它們是我的下一個任務。再次感謝 – Brackers

0

我的2美分

Dim f As File, fileStream As TextStream, filetext As String, NewLines() As String, Offset As Long 

Offset = 1 

Set fileStream = f.OpenAsTextStream(ForReading) 
filetext = fileStream.ReadAll 

filetext = Replace(filetext, vbCrLf, " ") 'make everything one line 
NewLines = Split(filetext, "PRICE") 'make a new set of lines based on PRICE 

For l = LBound(NewLines) To UBound(NewLines) 

    ActiveSheet.Cells(l + Offset, 1) = NewLines(l) 
Next l 

fileStream.Close 
Set fileStream = Nothing 
+0

嗨布拉德。我確定你的代碼工作得很好,但我似乎很難將它合併到我現有的代碼中。不過謝謝 – Brackers

相關問題