MS-Access / Getting Started

Writing Sequential Data to a File

In order to write data to a sequential file, you want to use either the Output mode, which creates a new file for writing, or the Append mode, which writes records to the end of a data file. Note that these are two separate lines of code.

Open "quiz1.dat" For Output As #1
Open "quiz.dat" For Append As #1

After opening a file for writing, you can use the Write function to write records.

Write #Filenumber, Fields

The Write function takes two parameters: #Filenumber and a list of fields. #Filenumber denotes the file number used in the Open function, and the Fields parameter is a list of strings, numbers, variables, and properties that you want to use as fields.

For example, if I want to create a data file and write quiz records to it, use the following syntax.

Open "quiz.dat" For Output As #1
Write #1, 1, "Is Visual Basic an Event Driven language?", "Yes"

Also use variable names for my fields list.

Write #1, liQuestionNumber, lsQuestion, lsAnswer

Either way, VBA outputs numbers as numbers and strings as strings surrounded with quotation marks.

Closing Data Files

As you may have guessed, closing a data file is an important part of file processing. Specifically, closing a data file performs the following operations:

  • Writes the EOF marker
  • When using the Output or Append mode, writes records to the physical file in the sequential order in which they were created
  • Releases the file number and buffer for memory conservation

To close a data file, simply use the Close function after all file processing has completed.

Close #FileNumber

The Close function takes the file number as its only parameter. For example, to close the file quiz.dat after writing one record, I could use the Close function:

Open "quiz.dat" For Output As #1

Write #1, 1, "Is Visual Basic an Event Driven language?", "Yes"

Close 1

If the Close function is used without any parameters, it closes all open sequential data files.

[Previous] [Contents] [Next]