Hiddenllyy
Hiddenllyy

Reputation: 179

VBA_using 'Line Input' but failed (Error 62: Input past end of file)

Good morning,

I've tried to write a code in order to: 1. Open a txt. file, which contains a list of files 2. Open the files in the list one by one 3.read the contents in each file and put it in the sheet

And my code is here:

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

You may find that the two part of Do While is exactly the same but the first one, for the list, runs well. And the second one, for the contents in the file, always failed. Could you please help me to check this? Thank you in advance!

Upvotes: 2

Views: 1590

Answers (1)

SierraOscar
SierraOscar

Reputation: 17637

The problem is here:

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

You're telling the code to loop through and Line Input from file #2 but the condition is based on reaching the end of the file in file #1.

As you're not actually moving through file #1 the statement EOF(1) will never be true - this loop will run and inevitably hit the end of file #2 at which point you will get the error

Input past end of file


To fix your problem:

try something like this instead:

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

Upvotes: 2

Related Questions