next up previous
Next: 15. Inputting from a Up: VisualBasic Previous: 13. WHILE/WEND Loops


14. Outputting to a Data File

If you have a lot of output from a program it is often useful to get the programme to write this output to a file for later use, rather than the screen. There are four steps to do this:

  1. Firstly, the programme selects where the output file will be written. This is optional, but if you don't specify the directory, it defaults to the directory which the Visual Basic programming suite sits in. When you start Visual Basic from the "Programming Languages" directory, this default directory is hidden away in a "systems" directory deep down many sub-directories. However, when you load a programme (i.e. form file) from blackboard) the default directory is your desktop. Here is an example form file which will output a number to a file on your Desktop.

  2. Secondly, it needs to "open" the file; i.e. tell the computer that there is going to be a file used by the program;

  3. Thirdly, it simply writes the variables to this file;

  4. Finally, it closes the file (Visual Basic may get upset if you don't do this...)

These four commands are listed below:

ChDrive "P:"
ChDir "\My_Directory"

Open "EXAMPLE.DAT" For Output As #1
Print #1, X
Close #1

Here the first two instructions select the drive and the directory where the output file is to be written. i.e. the ChDrive "P:" sets the drive to be the P: drive, and the ChDir "My_Directory" sets the directory within that drive to be My_Directory. Note that you must put the drive and directory name inside quotation marks (i.e. the ChDrive and ChDir must have a string following it). Note also that these ChDrive and ChDir lines are both optional. If you don't have them, then the default directory is used (see above).

Then the computer is told to open the file EXAMPLE.DAT and to give this file a number #1.

The third command simply tells the computer to write out the value of the variable X to this file, i.e. to the file #1.

Finally the file is closed.

Note that in the example above, the file number was 1, but you could have assigned almost any number to it. If you have more than one file open at the same time, you will obviously have to refer to them by different numbers.

You can easily generalise the above example so that it outputs more data than simply one number. The following example outputs 35 rows of data, each row consisting of two columns.

Open "EXAMPLE.DAT" For Output As #5

For I = 1 To 35
Print #5, I, I^2
Next I

Close #5

There are three steps to outputting to a data file: (i) Open the file; (ii) Print to the file; (iii) Close the file. Optionally, you may wish to specify which directory the file will be in before any of these steps.


next up previous
Next: 15. Inputting from a Up: VisualBasic Previous: 13. WHILE/WEND Loops
Chris Allton 2006-10-27