Return to VBA Code Examples

VBA – Read Text File Line by Line

This tutorial will demonstrate how to read content from text files line by line with VBA.

We can either read the text file as an entire file, or line by line.

Read Text File Line by Line

Text in a text file is usually made up of several lines, separated by delimiters. These can be a comma (“,”), a comma with space (“, “), a semicolon (“;”), a  semicolon with space (“; “),  a space (“ “),  a tab (vbTab) or in rare cases any other character such as a tilde (~). The lines are normally separated by a line break (vbCRLF).

The easiest way to read a text file line by line into our Worksheet in VBA is to select the first cell where we want the text to be put, and then run the following code:

This will put each line of the text file into a single cell in Excel.

VBA ReadTextFile Excel


We can also read a text file in VBA by using the FileSystemObject.  In the code below we have used late binding with the File System Object.  You can also create a reference to it in your VBA project.  See here for more information.

We can create a slightly more complicated loop if we want to separate the lines into cells by their delimiters.  Here we have used early binding in the code and declared the File System Object.

This will result in the lines being separated into individual cells in Excel as per the graphic below.

VBA ReadTextFile Delimiters


VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as

Learn More!