Open Text Files

Reading data from text files into Excel is probably the most common programming task in Excel. No, it’s not exciting (at all) but there is a surprising amount of data coming from text files into Excel. Tab-delimited and comma-delimited text files are a sort of universal data format—most systems can read and write those formats. Excel is very good at it.

First some basics. There are two sorts of text datafiles: delimited files (just mentioned) and fixed-width files. Delimited files use commas, tabs, semicolons, or some other character to separate fields of data. In fixed-width files, each field begins at a fixed location. If data in a field doesn’t fill that field, the rest of the field contains spaces.

Each line in a datafile represents a record. Line is an imprecise term, however. Different systems have different standards for what is considered a line. On Windows systems, a newline is indicated by the carriage-return and line-feed characters (Chr(13) and Chr(10) or vbCrLf in Visual Basic). On Macintosh and Linux systems, it’s just line feed (Chr(10)).

When Excel opens a text file, it needs to know how the fields and records are identified. Once it has that information, it can read the text file, place fields into columns, and create a new row for each record. Excel can guess at a lot of that—for example, it just assumes that the file was created by the operating system that Excel is currently running under—and you can see these assumptions by choosing File → Open ...

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.