VBA Guide to Interact with Text Files – Part – 2 of 2

.

[fusion_text]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 –

[highlight color=”yellow” rounded=”” class=”” id=””]Run time Error – 62 – Input past end of file.[/highlight]

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 🙂

[sharing tagline=” Did you like this article? Then share it with your friends… spread knowledge…” tagline_color=”green” title=”Share” link=”” description=”Learn All about interacting with Text Files in Excel VBA like opening, creating, writing, reading etc. from Text Files using Excel VBA code” pinterest_image=”” icons_boxed=”yes” icons_boxed_radius=”4px” color_type=”brand” box_colors=”” icon_colors=”” tooltip_placement=”” backgroundcolor=”#fff3dd” class=”” id=””][/sharing]

Buy a coffee for the author

Adsense

Download FREE Tools and Templates

There are many cool and useful excel tools and templates available to download for free. For most of the tools, you get the entire VBA code base too which you can look into it, play around it, and customize according to your need.

Dynamic Arrays and Spill Functions in Excel: A Beginner’s Guide
Dynamic Arrays and Spill Functions in Excel: A Beginner’s Guide

In today's tutorial, we'll be diving into the exciting world of dynamic arrays and spill functions in Office 365 Excel. These features have revolutionized the way we work with data, providing a more flexible and efficient way to handle arrays. I am going to explain...

How to Declare a Public Variable in VBA
How to Declare a Public Variable in VBA

While programming in VBA sometimes you need to declare a Public Variable that can store the value throughout the program. Use of Public Variable: Let's say you have 4 different Functions in your VBA Code or Module and you have a variable that may or may not be...

How to Copy content from Word using VBA

As many of us want to deal with Microsoft Word Document from Excel Macro/VBA. I am going to write few articles about Word from Excel Macro. This is the first article which opens a Word Document and read the whole content of that Word Document and put it in the Active...

What is Excel Formula?

Excel Formula is one of the best feature in Microsoft Excel, which makes Excel a very very rich application. There are so many useful built-in formulas available in Excel, which makes our work easier in Excel. For all the automated work, Excel Macro is not required. There are so many automated things can be done by using simple formulas in Excel. Formulas are simple text (With a Syntax) which is entered in to the Excel Worksheet Cells. So how computer will recognize whether it is a formula or simple text? Answer is simple.. every formula in Excel starts with Equal Sign (=).

You May Also Like…

2 Comments

  1. Pabloj

    Thanks for teaching us. Nice web. I apologize for my horrible english, aniway…
    What way should I take to, after converting JPG to TXT, look for a word to get “the words that follow” it ?
    Or what is the same… each line of the newly created TXT will have a separator ( I guess ) and “the words that follow” could be in the same line or in the next one.
    Or, even easier, which is the separator that separates lines when making those conversions ? Is it always ( JPG/GIF/etc.) the same separator ? Knowing this last point I can try doing the job by different ways (VLOOKUPs; DBfunctions, matrix formulas, loops, even some light AI, etc…).
    Thank you very much. Again, nice nice web.

    Reply
  2. YONG ZENG

    After output Excel as text file or XML, it is ready to use SQL to interact with output file. But thanks for your wonderful site and simple, easy tutorial to benefit readers to lean.

    Reply

Trackbacks/Pingbacks

  1. VBA Methods - To Export Excel Range, Table, Sheets as CSV File - […] Before we go in to details, I would like to recommend you guys to go through following tutorials –…
  2. Complete VBA Guide to Interact with Text Files with Examples - […] VBA Guide to Interact with Text Files – Part – 2 of 2 Excel Macro : Excel VBA code…

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Join and get a FREE! e-Book

Don't miss any articles, tools, tips and tricks, I publish here

You have Successfully Subscribed!

Pin It on Pinterest