The Wayback Machine - https://web.archive.org/web/20240525080944/https://www.geeksforgeeks.org/how-to-read-data-from-text-file-in-excel-vba/
Open In App

How to Read Data From Text File in Excel VBA

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

VBA Program to read a Text file line by line (Sales Data) and place it on a worksheet It provides a concise introduction to the process of importing data from text files into Microsoft Excel using Visual Basic for Applications (VBA). This introductory article serves as a starting point for individuals who want to automate the task of reading and processing data from external text files within an Excel workbook. It likely covers essential concepts such as variable declarations, file handling, and data extraction, setting the stage for readers to delve deeper into the specifics of VBA coding to accomplish this task efficiently. Overall, it offers readers a fundamental understanding of the topic and hints at the practical benefits of utilizing VBA for data manipulation in Excel.

Sales Data in Text File: 5 Fields [ Product, Qtr 1, Qtr 2, Qtr 3 and Qtr 4 ] and 25 Records (incl. header)

Sales data

VBA code will read a text file and place it on worksheet cells as below

Data-Set

VBA – Read Text File Line by Line

Declaring variables

Variables Data Type Comments
line String Read text file line by line
Filename String Input file name (Full path)
i Integer Iterator
value() String split the sentence by comma and store it in an array variable of type String

‘Variable declarations

Dim line As String, Filename As String, i As Integer, valueArr() As String

Initialize the “Filename” variable with full path and filename

‘Text file fullPath
Filename = “D:\Excel\ReadTextFile\sales.txt” ‘update your full file path
i = 1

Open the input file to read the text 

‘Open file
Open Filename For Input As #2

Read input file line by line

‘Read line by line – text file
While Not EOF(2)
Line Input #2, line

  • Split by a comma and store it in valuer ().  In our example, each line has 5 values concatenated with a comma.

‘split the line by comma separated, assigned in an array
valuesArr() = Split(line, “,”)

  • Add text to respective cells from values ().  Read each item in an array by its index value

Cells(i, “A”).Value = valuesArr(0)
Cells(i, “B”).Value = valuesArr(1)
Cells(i, “C”).Value = valuesArr(2)
Cells(i, “D”).Value = valuesArr(3)
Cells(i, “E”).Value = valuesArr(4)

Increment counter i, to move next line.

i = i + 1

  • Close while loop

Wend

Close file

‘Close file
Close #2

How to Read Text File Line by Line

Step 1: Open Excel

Step 2: Add a Shape

Add a shape (Read Text File) to your worksheet.

Add a Shape

Step 3: Right Click and Select Assign Macro

Right-click on “Read Text file” and “Assign Macro..”

Assign a Macro

Step 4: Select ReadTextFileLineByLine Macro

Assign a Macro

Step 5: Save your Excel File

Save your Excel file as “Excel Macro-Enabled Workbook”  *.xlsm

Save your Excel

Step 6: Click Read Text file 

Read "Text File"

Step 7: Adjust the Column Width

Adjust the column width in your Excel file.

Drag to adjust column widths

How to Read Text Files in Arrays in Excel

In Excel VBA, you can read text files into arrays by following these steps:

Step 1: Open Excel and Press ALT + F11 to Open the VBA Editor

Step 2: Insert a New Module

Insert a new module by clicking “Insert” > “Module.”

Screenshot-(239)

Insert a Module

Step 3: Enter the Below code in VBA window

Note: Please replace “C:\YourFolderPath\YourFile.txt” with the actual path of the text file you want to read. This code will read the lines from the text file and store them in the TextArray. It also includes an example of how to print the contents of the array to the Immediate Window for testing purposes. You can modify the code to perform any desired operations on the data stored in the array.

Step 4: Now Click on Run Module

FAQs

What is the purpose of reading data from a Text file in Excel VBA?

Reading data from a text file using Excel VBA allows you to import external data into your Excel workbook. This can be useful for data analysis, reporting, and integration of data from various sources.

How to open the Visual Basic for Applications (VBA) editor in Excel?

Press ‘Alt’ + ‘F11’ to open the VBA within Excel. This will bring up the VBA development environment where you can write and edit VBA code.

What is the SteamReader object in Excel VBA used for?

The SteamReader object is used to read data from a text file in a sequential manner. It provides methods for reading lines, characters, and other data from the file.

What are the limitations or considerations when reading data from a text file in Excel VBA?

Careful of memory usage when reading large text files into Excel, as excessive data can slow down your workbook or cause memory-related issues.



Similar Reads

VBA Subroutine in Excel - How to Call Sub in VBA?
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of
3 min read
How to Create Charts in Excel Using Worksheet Data and VBA?
Excel is an important software provided by Microsoft Corporation. This software belongs to one of the major software suites Office 365. In this software suite, there are other software are present like Word, PowerPoint, etc. They are called Office 365, as this software are mostly used for office purpose. But now the world has changed a lot. After t
7 min read
Variables and Data Types in VBA Excel
In a computer system, variables and data types are almost used in every program to store and represent data. Similarly, Excel VBA also has variables and data types to store and represent data and its type. In this article, we will learn about VBA variables, their scope, data types, and much more. VBA Variables VBA(Visual Basic for Application) vari
9 min read
Excel VBA | count() functions
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its var
2 min read
How to Use for Each Loop in Excel VBA?
A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: PartDescriptionelement Required (Must be mentioned). Variable is used to
3 min read
Excel VBA | sum() functions
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its var
2 min read
Excel VBA | Average() Functions
VBA (Visual Basic for Applications) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA, one can automate many tasks in excel and all other office softwares. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its v
2 min read
How to Declare and Initialize String Array in Excel VBA?
A string array is an array where we can store only string values in the array, with the help of a string array, we can store more than one string value. We can declare the string array in many ways like declaring a static string array, declaring a variant size array of string using the Array function, and a string array using the split function whi
2 min read
Trapping Dynamic Ranges in Excel VBA
Dynamic Ranges give the flexibility to work with more range of cells as compared to a specific range of cells which usually limits us to work with a particular range of cells. As the size of the data may change in an excel sheet so it is also necessary to change the range in the code dynamically for that dynamic ranges are used. We can trap dynamic
3 min read
VBA Strings in Excel
In the realm of Excel's Visual Basic for Applications(VBA), strings play a pivotal role in handling and manipulating text-based data. Strings serve as a fundamental data type used to store a sequence of characters, enabling the representation of textual information, numbers, symbols, and more. Understanding how VBA handles strings is essential for
8 min read