Connecting Tech Pros Worldwide Forums | Help | Site Map

How to read a file in VB - Part 1 - VB6, Line Input

Moderator
 
Join Date: Oct 2006
Location: Australia
Posts: 7,748
#1   May 16 '07
Here is a very simple example routine which reads a text file, one line at a time. This uses the built-in VB statements only. Later we will cover the FileSystemObject, which provides greater functionality at the expense of slightly greater code complexity.

This self-contained routine can be pasted into a code module and called from anywhere, including the immediate window. It will expect you to pass the name of a file (including the path if it isn't in the current directory) and will copy the contents of the file to the immediate window. Note it will also avoid, as far as possible, interfering with any other processing which may be going on at the time.

Expand|Select|Wrap|Line Numbers
  1. Public Sub DumpFile_V01(ByVal FileName As String)
  2.   Dim FileNo As Long
  3.   Dim LineNo As Long
  4.   Dim LineText As String
  5.  
  6.   FileNo = FreeFile ' Get next available file number.
  7.  
  8.   Open FileName For Input Access Read Shared As #FileNo
  9.   Do Until EOF(FileNo) ' Repeat until end of file...
  10.     Line Input #FileNo, LineText ' Read a line from the file.
  11.     LineNo = LineNo + 1
  12.     Debug.Print Format(LineNo, "00000"); ": "; LineText
  13.     DoEvents ' Allow Windows to handle other tasks.
  14.   Loop
  15.   Close #FileNo
  16. End Sub



Closed Thread