File input loop with accumulator


You have a file with data that you want to process. The amount of data in the file could change. You want to know something about the data set, like its total.


Initialize an accumulator variable. Loop while not EOF (end of file), reading data, and updating the accumulator each time through the loop. See the Explanation of this pattern for a flowchart and code.


An accumulator is a variable that accumulates information about a data set. Here's a flowchart and code that shows how to use an accumulator with a file input loop.


  1. 'Initialize accumulator.
  2. itemCount = 0
  3. itemTotal = 0
  4. 'Open data file for input.
  5. Open ThisWorkbook.Path & "\filename.txt" For Input As #1
  6. 'Loop over the file.
  7. Do While Not EOF(1)
  8.     Input #1, item
  9.     itemCount = itemCount + 1
  10.     itemTotal = itemTotal + 1
  11. Loop
  12. 'Close the file.
  13. Close #1