Read a fixed length text file

Step 1: define custom type for the record

Use a custom type to easily get information from your record.


Type Record 'TODO: define your fixed lenght record
 ID As Integer
 Name As String * 20
End Type

Step 2: Retrieve the record

Retrieve the record based on it's position

The VBA code below shows how you can read a single record based on it's position.


Dim strFilename As String: strFilename = "C:\temp\yourfile.txt"
Dim lngPosition As Long
Dim iFile As Integer: iFile = FreeFile
Open strFilename For Input As #iFile
Dim MyRecord As Record
Open strFilename For Random As #1 Len = Len(MyRecord)
lngPosition = 3 'TODO: set position
Get #1, lngPosition, MyRecord

Close #1 ' Close file.

Retrieve all records sequentially

If you don't specify the position argument in Get the first call will retrieve the first record, while each next call will retrieve the next until the end of the file (EOF).


Dim strFilename As String: strFilename = "C:\temp\yourfile.txt"
'Read file with fixed length records
Dim iFile As Integer: iFile = FreeFile
Open strFilename For Input As #iFile
Dim MyRecord As Record
Open strFilename For Random As #1 Len = Len(MyRecord)
Do While Not EOF(iFile)
    Get #iFile, , MyRecord
    With MyRecord
        
    End With
Loop
Close #iFile
Code VBA menu read text file contents into a string variable