Writing to a text file

Writing to a text file is very similar to reading from a text file in VB6 (possibly easier as you don't need to check for the end of the file).

Opening the file

First of all, you need to open the file. It's always a good idea to provide a full pathname (e.g. C:\My Folder\My Data\myFile.txt instead of just myFile.txt).

You need to give the file a file number so that you can refer to it later on. In the example below I've given mine the designation of file number 1 - by using #1.

Note the word Output - denoting that I want to use the file for output.

Open App.Path & "\data.txt" For Output As #1

Writing to the file

To write to the file you just use the command Print <file number>, <string>. This will write the <string> to the file and create a new-line in the file, ready for the next output.

If you wanted to output "Hello World" to your file and the file number was 1 then you would use the command:

Print #1, "Hello World"

Closing the file

It's important that you remember to close the file when you've finished writing to it, otherwise you might not be able to re-open the file later in your program. All you need to do is use the keyword Close, followed by the file number.

Close #1

Putting it all together

The Visual Basic code below creates a textfile called "test.txt" in the same folder as the project when the program is run. It then outputs the colours of the rainbow to the file before finally closing it. 


VB6 Example

Private Sub Form_Unload(Cancel As Integer)

    ' This sub is triggered when the program ends and
    ' the form is unloaded
    
    ' Open the text file for output
    Open App.Path & "\test.txt" For Output As #1
   
    ' Write all the colours to the textfile
    Print #1, "Red"
    Print #1, "Orange"
    Print #1, "Yellow"
    Print #1, "Green"
    Print #1, "Blue"
    Print #1, "Indigo"
    Print #1, "Violet"
 
   
    ' Close the file
    Close #1
   
End Sub