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, I could use the following syntax.

Open "quiz.dat" For Output As #1

Write #1, 1, "Is Visual Basic an Event Driven language?", "Yes" I could 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 quote marks.

0 0

Post a comment