VBA_using 'Line Input' 但失败(错误 62:输入超过文件末尾)

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

早上好,

我尝试编写代码以便: 1.打开一个txt。文件,其中包含文件列表 2.逐一打开列表中的文件 3.read将每个文件中的内容放入sheet

我的代码在这里:

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 的两个部分完全相同,但第一个部分(对于列表)运行良好。 而第二个,对于文件中的内容,总是失败。 你能帮我检查一下吗? 提前致谢!

问题在这里:

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

您告诉代码从文件 #2 循环并 Line Input 但条件是基于到达文件 #1.[=19 中的文件末尾=]

因为你实际上并没有在文件 #1 中移动,语句 EOF(1) 永远不会 为真 - 这个循环将 运行 和不可避免地到达文件末尾 #2 ,此时您将收到错误

Input past end of file


解决您的问题:

尝试这样的事情:

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