Search code examples
vbawhile-loopreadfileeofdo-loops

EOF VBA blocks me from accessing last line of my file


I am trying to loop through a text file. I do specific check on each line of this file to know if it will be pasted or not. I am using the following code. But using EOF blocks me from accessing the last line, which can be useful sometimes.

Dim buffer As String
Open file For Input As #1

Line Input #1, buffer
i = 1
j = 1

Do Until EOF(1) And i > coll(coll.Count)

    If i = coll(j) Then 
         ListSplit = Split(buffer, ",") 'Split the line with "," delimiter
         '...
         j=j+1
    End If

    Line Input #1, buffer
    i = i + 1

Loop 

Close #1

Solution

  • Structure your logic like this:

       Open file For Input As #1
       
       Do
          Line Input #1, buffer
          Debug.Print buffer  'do your work
       Loop Until EOF(1)
       
       Close #1
    

    The issue with the code you posted is that the last line is read, which sets EOF, and then you loop. The condition is evaluated and the loop is exited.