【问题标题】:Why after running Windows updates do I get "Run-Time Error 62 Input Past End of File"?为什么在运行 Windows 更新后会出现“运行时错误 62 输入超过文件结尾”?
【发布时间】:2019-09-17 23:16:11
【问题描述】:

知道为什么我在使用 Input 函数时不断收到运行时错误 62 Input past end of file 错误,并使用以下代码。帮助功能告诉我文件是二进制文件,我应该使用 LOF 或 Seek,但似乎都不起作用。在最近对我的计算机进行 Windows 和 Microsoft 更新之前,此代码运行良好。

  Dim fldr As FileDialog
    Dim sItem As String

      Set fldr = Application.FileDialog(msoFileDialogFilePicker)
      With fldr
          .Filters.Clear
          .Filters.Add "All files", "*.*"
          .Title = "Select a CFG File to Convert fromatting from R2013 to 1991."
        .AllowMultiSelect = False
        .InitialFileName = ActiveWorkbook.Path 'Application.DefaultFilePath
        If .Show <> -1 Then Exit Sub
        sItem = .SelectedItems(1)
    End With

  set fldr = Nothing

   Open sItem For Input As #1
   dataArray = Split(Input(LOF(1), #1), vbLf)
   Close #1

    If Len(dataArray(2)) - Len(Replace(dataArray(2), ",", "")) = 9 Then
    MsgBox "It appears the comtrade file format already conforms to the 1991 standard version." & vbNewLine & "" & vbNewLine & "Conversion was Aborted."
    Exit Sub
    End If

我正在尝试计算所选文件第 3 行中逗号的数量。

【问题讨论】:

  • 不是问题,但“fromatting”应该是“formatting”;-)
  • FWIW 非常相似的文件阅读器代码以前被炸毁,请参阅 here - 我怀疑 Windows/Office 更新与它有什么关系。

标签: excel vba


【解决方案1】:
dataArray = Split(Input(LOF(1), #1), vbLf)

单行代码就需要做很多工作。

您没有验证整个文件,仅验证第二行。您还在硬编码文件句柄#,这可能会导致其他问题 - 使用 FreeFile 函数从 VBA 获取免费文件句柄,而不是假设 #1 可用。或者更好的是,改用更高抽象的 FileSystemObject(参考 Microsoft Scripting Runtime 库):

With New Scripting.FileSystemObject
    With .OpenTextFile(filename, ForReading)
        Dim contents As String
        contents = .ReadAll
    End With
End With
Dim lines As Variant
lines = Split(contents, vbNewLine)

或者,不引用 Scripting 库:

Const ForReading As Long = 1

With CreateObject("Scripting.FileSystemObject")
    With .OpenTextFile(filename, ForReading)
        Dim contents As String
        contents = .ReadAll
    End With
End With
Dim lines As Variant
lines = Split(contents, vbNewLine)

请注意,当您针对 Object 编写代码时,成员调用是后期绑定的:您不会获得 IntelliSense/自动完成功能,也不会获得任何编译时验证;拼写错误将愉快地编译(并在运行时因错误 438 而爆炸)。到处都喜欢早期绑定的代码——不过我想不出对Scripting库使用后期绑定的理由,因为这个库在本世纪建造的每台Windows机器上都是完全相同的。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2018-05-28
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多