• To read variables from a sequential file, we essentially reverse the write
procedure. First, open the file using:
Open SeqFileName
For Input As #N
where N is an integer file number and SeqFileName is a complete file path. The
file is closed using:
Close N
• The Input statement is used to read in variables from a sequential file.
The format is:
Input #N, [variable list]
The variable names in the list are separated by commas. If no variables are listed,
the current line in the file N is skipped.
• Note variables
must be read in exactly the same manner as they were written. So, using our previous
example with the variables A, B, C, and D, the appropriate statements are:
Input #1, A, B, C
Input #1, D
These two lines read the variables A, B, and C from the first line in the file
and D from the second line. It doesn’t matter whether the data was originally
written to the file using Write or Print (i.e. commas are ignored).
Quick Example: Reading Variables from
Sequential Files
-
Start a new project or simply modify the previous quick example.
-
Attach the following code to the Form_Load procedure.
This code reads in files created in the last quick example.
Private Sub Form_Load()
Dim A As Integer, B As String, C As Single, D As Integer
Open "Test1.Txt" For Input As #1
Input #1, A, B, C
Debug.Print "A="; A
Debug.Print "B="; B
Debug.Print "C="; C
Input #1, D
Debug.Print "D="; D
Close 1
End Sub
Note the Debug.Print statements and how you can add
some identifiers (in quotes) for printed information.
-
Run the program. Look in the debug window and note the variable values. Save
the application, if you want to.
-
Rerun the program using Test2.Txt as in the input
file. What differences do you see? Do you see the problem with using Print and
string variables? Because of this problem, I almost always use Write (instead
of Print) for saving variable information to files. Edit the
Test2.Txt file (in Notepad), putting quotes around the words Visual Basic.
Rerun the program using this file as input - it should work fine now.