0

Any idea why I keep getting a Run -time error 62 Input past end of file error with the following code when using the Input function. The help function tells me the file is in binary and I should use either LOF or Seek however neither seems to work. This code worked fine until a recent Windows and Microsoft update to my computer.

  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

I'm trying to count the number of commas in line 3 of the selected file.

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
Josh
  • 1
  • 1

1 Answers1

0
dataArray = Split(Input(LOF(1), #1), vbLf)

That's a lot of work for a single line of code.

You're not validating the entire file, only the second line. You're also hard-coding a file handle#, and that can cause other problems - use the FreeFile function to get a free file handle from VBA instead of assuming #1 is available. Or better, use the higher-abstraction FileSystemObject instead (reference the Microsoft Scripting Runtime library):

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)

Or, without referencing the Scripting library:

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)

Note that when you code against Object, member calls are late-bound: you don't get IntelliSense/autocompletion, and you don't get any compile-time validation; typos will merrily compile (and blow up at run-time with error 438). Prefer early-bound code everywhere - I can't think of a reason to use late binding against the Scripting library though, since that library is the exact same on every Windows machine built this century.

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235