2016-05-31 78 views
2

早上好,VBA_using「線路輸入」,但失敗(錯誤62:輸入過去文件的結尾)

我試圖以寫代碼: 1.打開一個txt。文件,其中包含文件 2.打開列表中的一個接一個 3.read每個文件中的內容的文件的列表,並把它放在表

我的代碼是在這裏:

Private Sub Boutton_Importer_Click() 

list_de_controle = "TEXT;" & listPath 
Open listPath For Input As #1 'open the list 

Do While Not EOF(1) 'read the list 
    Line Input #1, nom_de_Fich 
    ActiveCell = nom_de_Fich 
    ActiveCell.Offset(0, 1).Select 

    Open nom_de_Fich For Input As #2 'open a file in the list 

    Do While Not EOF(1) 'read the contents in the list 
     Line Input #2, contenu 
     ActiveCell = contenu 
     ActiveCell.Offset(0, 1).Select 
    Loop 
    Close #2 

    ActiveCell.Offset(1, 0).Select 'go to the line below 
    ActiveCell.End(xlToLeft).Select 
Loop 
Close #1 
End Sub 

您可能會發現Do While的兩部分完全相同,但列表中的第一部分運行良好。 而第二個,對於文件中的內容,總是失敗。 你能幫我檢查一下嗎? 提前謝謝!

+0

我忘記了一些東西,在列表中的第一個文件可以打開,所有的內容可以以表來讀取,但接下來的文件可以不會被打開。所以我認爲問題在於EOF無法確定它是否已經達到最終結果。 – Hiddenllyy

回答

2

的問題是在這裏:

Do While Not EOF(1) 'read the contents in the list 
    Line Input #2, contenu 
    ActiveCell = contenu 
    ActiveCell.Offset(0, 1).Select 
Loop 
Close #2 

你通過和Line Input從文件#2告訴代碼迴路,但條件是基於到達文件的末尾文件#1

如果你還沒有真正通過文件#1語句移動EOF(1)永遠是真實的 - 這個循環將運行並不可避免地大賣文件#2結束,此時你會得到錯誤

文件的輸入過去結束


解決您的問題:

嘗試這樣的事情,而不是:

Sub Foo() 

Dim textFile1 As Byte 
Dim textFile2 As Byte 
Dim tfArray1 As Variant 
Dim tfArray2 As Variant 

textFile1 = FreeFile 

Open listPath For Input As #textFile1 
    tfArray1 = Split(Input(LOF(textFile1), textFile1), vbCrLf) 
Close #textFile1 

For Each tfile In tfArray1 

    textFile2 = FreeFile 

    Open tfile For Input As #textFile2 
     tfArray2 = Split(Input(LOF(textFile2), textFile2), vbCrLf) 
    Close #textFile2 

    Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Resize(UBound(tfArray2) + 1, 1).Value = _ 
     WorksheetFunction.Transpose(tfArray2) 

Next 

End Sub 
+0

非常感謝!我試圖改變EOF(1)到EOF(2),並且它工作。但我不知道這是否會導致一些問題? – Hiddenllyy

+0

不應該這樣做 - 但我更新了我的答案,以包含更好的方式來完成您試圖實現的目標,所以如果您願意,請嘗試一下。不要忘記標記爲答案,如果它幫助 –

+0

我看到了!我會試一試。當然,我會給出一個印記!非常感謝! – Hiddenllyy