MS-Access / Getting Started

Reading Sequential Data from a File

If you want to read records from a data file, you must use the Input parameter with the Open function.

Open "quiz.dat" For Input As #1

Once the file is opened for input, use the Input function to retrieve fields from the file.

Input #Filenumber, Fields

The Input function takes two parameters: #Filenumber and a list of fields. For example, if you want to read the first record in a data file called quiz.dat (assuming quiz.dat contains three fields for each record), you could use the following program statements.

Dim liQuestionNumber as Integer
Dim lsQuestion as String
Dim lsAnswer as String

Open "quiz.dat" For Input As #1

Input #1, liQuestionNumber, lsQuestion, lsAnswer

Notice that I pass three variables as the field list to the Input function. These variables hold the contents of the first record found.

By now, read all records in a data file?" The answer involves something new and something old. First, you must use a loop to search through the data file. Second, your loop's condition should use the EOF function.

The EOF (end of file) function tests for the end of the data file. It takes a file number as a parameter, returning a True Boolean value if the end of the file is found or False if the end of file has not been reached.

To test for the end of file, the EOF function looks for an EOF marker placed at the end of a file by the Close function. I discuss closing data files later in the tutorial.

Dim liQuestionNumber as Integer
Dim lsQuestion as String
Dim lsAnswer as String

Open "quiz.dat" For Input As #1

Do Until EOF(1)
    Input #1, liQuestionNumber, lsQuestion, lsAnswer
    List1.AddItem "Question number: " & _
      liQuestionNumber & lsQuestion
Loop

The preceding loop iterates until the EOF function returns a True value. Inside the loop, each record is read one at a time. After a record is read, the print method of a picture box control is used to output two of the fields (liQuestionNumber and lsQuestion) for display.

[Previous] [Contents] [Next]