Dear Friends,

I am back with the second part of the tutorial- VBA Guide to Interact with Text Files – Part – 1 of 2. This is the final part of this tutorial.
In previous article, mainly we learn about How to Open a Text File and How to write to Text File using VBA code. There were some other stuff as well which we discussed in detail. I would recommend to read my previous article before reading this article.

Topics covered in this Article

Click on the below links to directly jump to that section…

1. Read data from Text File using VBA Code – Input Statement

As I mentioned in my previous article, to read a Text File, we should open the existing Text File in Input Mode.. To know more about How to open Text Files in Excel VBA, read this article.

This is very important to know that, Input statement is used to read a Text File which is produced or written by Write statement while writing it via VBA code. As you know from the previous article, Write statement, writes the data in Text file in comma separated columns. Therefore, you will see that while reading the data from Text file, each comman separated data is stored in each variable specified in the below Syntax.

Let see the syntax of Input Statement which is used to read an existing Text File..

Syntax of Input Statement to Read data from Text File in Excel VBA

Input #FileNumber, DataInput1, DataInput2, DataInput3

Where:

#FileNumber :

When Text files are opened then windows recognize them by a unique integer value. Valid range of Integers for this parameter is between 1 to 511.
As I mentioned above, it should be a unique integer, it is challenging for you to give a fixed number here in case you are dealing with multiple text files. To overcome this challenge you can use a function called FreeFile(). Click here to know more about FreeFile() Function.

DataInput 1, 2, 3.. etc

Comma separated data which is stored in the Text file gets stored automatically in these DataInput variables provided.
Note: You can use one or more than one variables in this statement based how many comma separated data you want to read from the Text File. Therefore it is possible that there are 100s of columns are there in each rows in a TextFile but you can read only one or more specific data using Line statement.

Example:

Let’s take an example and understand how Input statement works for reading data from a Text File.

This is the text file which we want to read the data from and put it in to Excel.
VBA Code to read Text File

using the below code, we will read this text file and store all data row by row in an excel sheet. (Lat’s say Input sheet)



Sub ReadTextFileUsingInputStatement()

Dim sFilePath As String
Dim iRow As Integer
Dim OrderDate As Date
Dim OrderPriority As String
Dim OrderQuantity As Integer
Dim Discount As Double
Dim ShipMode As String
Dim CustomerName As String
Dim ShipDate As Date
    
    iRow = 2
    sFilePath = "C:\Users\vmishra\Desktop\LEM.txt"
    ' unique file number to access the file uniquely
    filenumber = FreeFile
    ' to check if file name LEM.txt exists
    ' if not, end the program
    If (VBA.Len(VBA.Dir(sFilePath))) = 0 Then MsgBox "File Does not exists": End
    ' Open the TextFile in Input mode
    ' in order to write in something
    Open sFilePath For Input As #filenumber
    
    ' Now using do while loop, traverse the Text file
    ' till it finds the End of the file.
    Do
    ' Now read the Text file data in each of the corresponding
    ' variables. As soon as below statement gets executed,
    ' corresponding data like OrderDate, ShipMode etc gets
    ' stored in the respective variables
    Input #filenumber, OrderDate, OrderPriority, OrderQuantity, Discount, ShipMode, ShipDate
    ' Now store these data in excel columns for each row.
    With Sheets("Input")
        .Cells(iRow, 1).Value = OrderDate
        .Cells(iRow, 2).Value = OrderPriority
        .Cells(iRow, 3).Value = OrderQuantity
        .Cells(iRow, 4).Value = Discount
        .Cells(iRow, 5).Value = ShipMode
        .Cells(iRow, 6).Value = CustomerName
        .Cells(iRow, 7).Value = ShipDate
    End With
    ' go to the next row in Excel sheet
    iRow = iRow + 1
    ' Go one by one till the last line of the file
    Loop Until EOF(filenumber)
    
    ' Close the file once all data
    ' is written in text file
    Close #filenumber
End Sub


In the above code you can see, I have used a function called EOF. Let’s have a quick look what this function is and why is it important to use?

What is EOF Function

EOF() is a Boolean type function which checks if control has reached to the end of the Text File while reading lines in the text file.

Syntax of EOF File

EOF(FileNumber)
Where FileNumber is same as explained above. It is an integer type variable.

This function returns a Boolean – True/False. If control reaches to an end then, it returns True when it reaches to the end of the file. Till then it always returns False

Why EOF() is important to use?

In case you do not use EOF() to find the end of the text file – as soon as control reaches to the end of the text file, it tries to read something which does not exist and it gives a run time error –

Run time Error – 62 – Input past end of file.

After running the above code, this is what you get in your excel sheet

Read Text File in Excel VBA

Read Text File in Excel VBA

From the above example of Input statement, you can see, it is not reading the whole line at once. You can read specific data from a line. But what if you want to read the whole line at once? Yes, it is possible to do by using Line Input statement. Let’s learn about it..

2. Read data from Text File using VBA Code – Line Input Statement

As the name suggests, using this statement you can read the whole line at once and it gets stored in a single variable. Unlike Input statement, as explained above, you do not need to define multiple variable to store the data.
Line Input Statement should be, ideally, used to read the Text file which has different data which are separated by a delimiter. So that once you read the whole line by using Line Input statement and data is stored in a single variable then you can easily split data by using Split function.

Let see the syntax of Line Input Statement which is used to read an existing Text File..

Syntax of Line Input Statement to Read data from Text File in Excel VBA

Line Input #FileNumber, LineData

Where:

#FileNumber :

When Text files are opened then windows recognize them by a unique integer value. Valid range of Integers for this parameter is between 1 to 511.
As I mentioned above, it should be a unique integer, it is challenging for you to give a fixed number here in case you are dealing with multiple text files. To overcome this challenge you can use a function called FreeFile(). Click here to know more about FreeFile() Function.

LineData

Variable to store data of a line in Text file. It stores all data of a line.

Example:

Let’s take an example and understand how Line Input statement works for reading data from a Text File.

This is the text file which we want to read the data from and display a message with meaning full data after splitting it.
As you can see in the below Text file, Name, Date of Birth, City and Role of a person in stored in a semicolon (;) delimited format.
Line Input statement will read the whole line in a single variable and then by using the Split () function., we will get all the parameters like name, date of birth etc.. separately.
Data Stored in Text File - Delimited format

using the below code, we will read this text file first line and display the data in a message box


Sub ReadTextFileUsingLineInputStatement()

Dim sFilePath As String
Dim lineData As String
Dim personalDetails
Dim message As String
    
    sFilePath = "C:\Users\vmishra\Desktop\PersonalDetails.txt"
    ' unique file number to access the file uniquely
    filenumber = FreeFile
    ' to check if file name LEM.txt exists
    ' if not, end the program
    If (VBA.Len(VBA.Dir(sFilePath))) = 0 Then MsgBox "File Does not exists": End
    ' Open the TextFile in Input mode
    ' in order to write in something
    Open sFilePath For Input As #filenumber
    
    ' Using Line Input statement
    ' read the first line and whole
    ' text will get stored in one variable - lineData
    Line Input #filenumber, lineData
    
    ' Since data is stored in a semicolon delimited format
    ' let's split it and store the data in an array formt
    ' using split() function
    personalDetails = Split(lineData, ";")
    
    ' using the array data create the meaning full
    ' message which can be shown to the user.
    message = "Name : " & Chr(9) & personalDetails(0) & vbNewLine
    message = message & "DOB : " & Chr(9) & personalDetails(1) & vbNewLine
    message = message & "City : " & Chr(9) & personalDetails(2) & vbNewLine
    message = message & "Role : " & Chr(9) & personalDetails(3) & vbNewLine
    MsgBox message
    
    ' Close the file once all data
    ' is written in text file
    Close #filenumber
End Sub

Result: After running the above code

After running the above code, you will see the following message box.
Read Text File - Line Input statement

Last part of this tutorial- Complete guide to interact with Text Files using Excel VBA is ended here.

I would really appreciate, if you provide your feedback. Do let me know by writing your comment here in the comment section of this article. If you would like more of these kind of detailed articles/tutorials covering a specific topic.. do let me know.

Thanks 🙂

cover3d_0-89071700_1484285537__1_

Join over 10, 000+ Excel VBA Enthusiasts & get this FREE e-Book Now!