【问题标题】:VBA_using 'Line Input' but failed (Error 62: Input past end of file)VBA_using 'Line Input' 但失败(错误 62:输入超过文件末尾)
【发布时间】:2016-05-31 08:36:48
【问题描述】:

早上好,

我尝试编写代码以: 1.打开一个txt。文件,其中包含文件列表 2.一个一个打开列表中的文件 3.读取每个文件中的内容,放入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 的两部分完全相同,但对于列表,第一部分运行良好。 第二个,对于文件中的内容,总是失败。 你能帮我检查一下吗? 提前谢谢!

【问题讨论】:

  • 我忘记了一件事,列表中的第一个文件可以打开,所有内容都可以读入工作表,但下一个文件无法打开。所以我认为问题在于 EOF 无法确定它是否已经结束。

标签: excel input eof vba


【解决方案1】:

问题出在这里:

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 中的文件末尾。

由于您实际上并未在文件 #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

【讨论】:

  • 非常感谢!而且我尝试将 EOF(1) 更改为 EOF(2),并且它有效。但是不知道会不会出问题?
  • 不应该这样做 - 但我更新了我的答案,以包括一种更好的方法来做你想要实现的目标,所以如果你愿意,可以尝试一下。如果有帮助别忘了标记为答案
  • 我明白了!我会试一试。我当然会打分!非常感谢!
  • 下午好,抱歉耽搁了,我的项目快完成了,我已经尝试了你的代码,但它显示了一条错误消息:下标超出范围。我试图将 LOF 更改为 EOF 但仍然失败。那你能看一下吗?
  • 这是 tfarray1 = Split(Input(LOF(textfile1), textfile1), vbCrLf)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多